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
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.