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

java, reflection

Solution

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.

Problem

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 Foo(); ``` is it possible to implement a method that can find the names of those variables, like so: ``` public void baz(Foo... foos) { for (Foo foo: foos) { // Print the name of each foo - b, a, and r System.out.println(***); } } ``` EDIT: This question is different from Is there a way in Java to find the name of the variable that was passed to a function? in that it more purely asks the question about whether one can use reflection to determine the name of a local variable, whereas the other question (including the accepted answer) is more focused on testing values of variables.

Original source

Related problems