Tuesday 13 October 2015

How to access the name of Private Fields?

Accessing name of Private Fields

To access a value of private/public field in Reflection, you need the name of this field.

To obtain the name of private fields, call the Class.getDeclaredField(String name) or Class.getDeclaredFields() method. The methods Class.getField(String name) and Class.getFields() methods only return public fields.

The name of fields are needed in marshaling/demarshalling algorithms and Java object to JSON /XML conversion.


package reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
class PrivateObject2 {
      private String privateField1;
      private String privateField2;

      public String publicField1;
      public String publicField2;
}

public class TestFieldList {
      public static void main(String[] args) {

            // to get only public fields
            Field[] fields = PrivateObject2.class.getFields();
            for(Field field : fields) {
                  System.out.println(field.getName());
            }
             System.out.println(“++++++++++++++++++”);
            // to get public as well as private fields
            Field[] allFields = PrivateObject2.class.getDeclaredFields();
            for (Field field : allFields) {
                  // check whether the is private.
                  if (Modifier.isPrivate(field.getModifiers())) {
                        System.out.println(field.getName());
                  }
            }
      }
}
Output:
      publicField1
      publicField2
      ++++++++++++++++++
      privateField1
      privateField2

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...