Is it possible to loop through a classes members in java?
Well, you can do it with reflection:
for (Field field : clazz.getFields())
{
...
}
(Or the equivalent for methods etc.)
You can then get the field values for a specific instance, or static values.
It does, it a bit of hassle though.
You have to use reflection.
See: Class.getDeclaredFieds()
Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object
You can see an example here
There are three ways of obtaining a Field object from a Class object.
Class cls = java.awt.Point.class;
// By obtaining a list of all declared fields.
Field[] fields = cls.getDeclaredFields();
// By obtaining a list of all public fields,
// both declared and inherited.
fields = cls.getFields();
for (int i=0; i<fields.length; i++) {
Class type = fields[i].getType();
process(fields[i]);
}
// By obtaining a particular Field object.
// This example retrieves java.awt.Point.x.
try {
Field field = cls.getField("x");
process(field);
} catch (NoSuchFieldException e) {
}
See the Class class definition for more options.
Yes, use the Reflection API. Particularly, check the getFields
and getMethods
methods from Class
.