开发者

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

开发者 https://www.devze.com 2022-12-09 18:18 出处:网络
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

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.


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.


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.


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

https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/reflect/package-summary.html

0

精彩评论

暂无评论...
验证码 换一张
取 消