mercredi 24 mai 2017

Use reflection API to get field names and values

I'm creating a number of POJOs and have to create toString() methods for each. Instead of hand-coding each, I thought it would be easier to create a class to do the work for me using the reflection API -- create the functionality in one place and use it in each POJO.

All fields in the POJOs are private. The POJOs are Java object representations of JSON objects.

The requirements are to traverse the fields in a class, and list the fields along with the values.

I'm currently testing the functionality on a class called ChannelResource.

Here is the class that I'm using to list field names and values:

    import java.lang.reflect.Field;
    public class ToStringMaker {
      public ToStringMaker( Object o) {

      Class<? extends Object> c = o.getClass();
      Field[] fields = c.getDeclaredFields();
      for (Field field : fields) {
          String name = field.getName();            
          try {
            System.out.format("%n%s: %s", name, field.get(o));
          } catch (IllegalArgumentException e) {
            e.printStackTrace();
          } catch (IllegalAccessException e) {
            e.printStackTrace();
          }
      }
  }}

I'm passing an instance of the ChannelResource class to the constructor.

The compiler does not like field.get(o) in this line:

    System.out.format("%n%s: %s", name, field.get(o));

The compiler says:

    java.lang.IllegalAccessException: Class ToStringMaker can not access a member of class ChannelResource with modifiers "private"

ToStringMaker works if I make all members public, but I'd really rather not do that. Is there another way to get the value of a private field?

I know that the Apache organization has something that creates the toString functionality, but I don't like the format.





Aucun commentaire:

Enregistrer un commentaire