开发者

Enumerate Java Fields

I have a Java class with ~90 fields. I want to be able to do things to every field (generate an XML开发者_StackOverflow社区 element for instance) without writing the same 5 lines of code with slight substitutions 90 times. In Objective C I think you can get to instance variables in ways similar to accessing Dictionary elements (ObjectForKey). Is there anything similar in Java such that I can get an array of the fields then do something to each of them?


Yes, it's called Reflection API.

In particular, MyClass.class.getDeclaredFields() will return a full list of fields declared by this class (see API for details)


Here's another approach: Use the Introspector API with the JDK to obtain bean-like properties of a class. This is helpful if you have getters and setters for your class and do not want to access the private fields directly. Obtain a BeanInfo via the Introspector and get all the propertyDescriptors from it. To find getter of that property.

I'll have to admit that using this API is a bit cumbersome and reflection (suggested by Nikita Rybak) is more straight forward.

But there's a utility Apache BeanUtils that does all the hardwork internally so working with beans becomes simple.

Add:

If you are using the reflection API, I'd suggest you annotate your bean fields or your getters with a custom annotation.

public class MyClassWith90Fields {

   @XmlSerialize("name")
   private String screenName;  // shoudl serialize as <name>...</name>

   @XmlSerialize
   private String email;  // shoud serialize as <email>...</email>

   @XmlSerializeIgnore
   pirvate boolean flag; // shoud not serialize as annotated as ignore
}

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @annotation XmlSerialize {
   public String value;
}

Once done, your generation code can check (using reflection) annotated fields and serialize them to XML appropriately.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜