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.

有帮助吗?

解决方案

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

其他提示

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

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top