How to get names of all private data members in a class

3k views Asked by At

I need a function that will return the names of all the private data members in my class as strings (perhaps in an array or list?), where each string is the name of a private, non final data member in my class. The non final condition is optional, but it would be nice.

1) Is this even possible? I think there is a way to retrieve all method names in a class, so I think this is possible as well.

2) I know I am asking for a hand out, but how do I do this?

EDIT

I have NO idea where to begin.

It seems java.lang.reflect is a good place to begin. I have started researching there.

3

There are 3 answers

4
user2336315 On BEST ANSWER

This should do the trick. Basically you got in a List all the fields of your class, and you remove the one who are not private. :

public static void main(String [] args){
    List<Field> list = new ArrayList<>(Arrays.asList(A.class.getDeclaredFields()));

    for(Iterator<Field> i = list.iterator(); i.hasNext();){
        Field f = i.next();
        if(f.getModifiers() != Modifier.PRIVATE)
            i.remove();
    }
    for(Field f : list)
        System.out.println(f.getName());
}

Output :

fieldOne
fieldTwo

Class A :

class A {
    private String fieldOne;
    private String fieldTwo;

    private final String fieldFinal = null;

    public char c;
    public static int staticField;
    protected Long protectedField;
    public String field;
}
0
M21B8 On
Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
  field.setAccessible(true); // You might want to set modifier to public first.
  Object value = field.get(someObject); 
  if (value != null) {
    System.out.println(field.getName() + "=" + value);
  }
}
2
Ashish Bindal On

You can access all public methods by Class.getDeclaredMethods() but in order to access private method you have to know the names of private methods.

To access private methods:

 Method privateMethod = MyObj.class.
    getDeclaredMethod("myPrivateMethod", null); //return private method named "myPrivateMethod"

 privateMethod.setAccessible(true); //turn off access check for reflection only

 Object o = privateMethod.invoke(MyObj, null); //call private method