Java Reflection: How to get the name of a variable?

后端 未结 8 2379
一生所求
一生所求 2020-11-22 00:28

Using Java Reflection, is it possible to get the name of a local variable? For example, if I have this:

Foo b = new Foo();
Foo a = new Foo();
Foo r = new Fo         


        
8条回答
  •  悲哀的现实
    2020-11-22 01:30

    It is not possible at all. Variable names aren't communicated within Java (and might also be removed due to compiler optimizations).

    EDIT (related to comments):

    If you step back from the idea of having to use it as function parameters, here's an alternative (which I wouldn't use - see below):

    public void printFieldNames(Object obj, Foo... foos) {
        List fooList = Arrays.asList(foos);
        for(Field field : obj.getClass().getFields()) {
             if(fooList.contains(field.get()) {
                  System.out.println(field.getName());
             }
        }
    }
    

    There will be issues if a == b, a == r, or b == r or there are other fields which have the same references.

    EDIT now unnecessary since question got clarified

提交回复
热议问题