List Java fields

I have a Java class with ~ 90 fields. I want to be able to do something in each field (for example, generate an XML element) without writing the same 5 lines of code with small replacements 90 times. In Objective-C, I think you can get instance variables in ways similar to accessing dictionary elements (ObjectForKey). Is there something similar in Java, so that I can get an array of fields and then do something for each of them?

+3
source share
2 answers

Yes, it is called the Reflection API .

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

+5
source

: API- Introspector JDK bean - . , , . BeanInfo Introspector propertyDescriptors. getter .

, API ( ) .

Apache BeanUtils, , beans .

API , bean .

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;
}

( ) XML.

+1

Source: https://habr.com/ru/post/1764801/


All Articles