Q:

Is it possible to loop through a classes members in java?

I have a DTO that has a whole bunch of members. I was wondering if Java supports the idea of a for(in) for the class.  I don't think it does, but it would save me a ton of grief if it did, so, I figured I'd toss the question out there.

A:

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.

A:

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.

A:

Yes, use the Reflection API. Particularly, check the getFields and getMethods methods from Class.

