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

后端 未结 8 2372
一生所求
一生所求 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:23

    As of Java 8, some local variable name information is available through reflection. See the "Update" section below.

    Complete information is often stored in class files. One compile-time optimization is to remove it, saving space (and providing some obsfuscation). However, when it is is present, each method has a local variable table attribute that lists the type and name of local variables, and the range of instructions where they are in scope.

    Perhaps a byte-code engineering library like ASM would allow you to inspect this information at runtime. The only reasonable place I can think of for needing this information is in a development tool, and so byte-code engineering is likely to be useful for other purposes too.


    Update: Limited support for this was added to Java 8. Parameter (a special class of local variable) names are now available via reflection. Among other purposes, this can help to replace @ParameterName annotations used by dependency injection containers.

提交回复
热议问题