tags:

views:

276

answers:

5

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.

+3  A: 

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

JG
A: 

You can use reflection to get all the members and functions.

Maybe you need to ask yourself why that DTO has so many members that you think this is necessary. Could be time to refactor.

duffymo
+12  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.

Jon Skeet
+1 for conciseness.
Thorbjørn Ravn Andersen
much obliged. Thanks.
Dr.Dredel
A: 

Take a look at the reflection framework whereby you can introspect the class for this information.

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/reflect/package-summary.html

Xepoch
+4  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.

OscarRyz