简体   繁体   English

如何获取类中所有私有数据成员的名称

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

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? 1)这有可能吗? 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? 2)我知道我要伸出援助之手,但是我该怎么做?

EDIT 编辑

I have NO idea where to begin. 我不知道从哪里开始。

It seems java.lang.reflect is a good place to begin. 似乎java.lang.reflect是一个不错的起点。 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 : 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. 您可以通过Class.getDeclaredMethods()访问所有公共方法,但是要访问私有方法,您必须知道私有方法的名称。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM