Easwaramoorthy Kanagaraj
Easwaramoorthy Kanagaraj

Reputation: 4213

Can I get information about the local variables using Java reflection?

I need to know the type of the local variables. I am using Java reflection, using which I could not get it. Can you please let me know how to know the type/name of the local variables.

Can I get information about the local variables using Java reflection?

Upvotes: 22

Views: 20084

Answers (5)

Stephen C
Stephen C

Reputation: 718678

Assuming that you are talking about a method or constructor's local variables, you cannot find out about them using reflection. You have to either

  • use a bytecode library such as BCEL or ASM, or
  • use one of the remote debugger APIs.

The latter will allow you to access the values of the local variables, but only while the JVM is suspended by the debug agent.

Both of these approaches rely on the classes in question being compiled with debug information. Specifically, the classes need to be compiled with "local variable debugging information"; e.g. using javac -g .... The "vars" debug information is not included by default.

Upvotes: 21

Hunter McMillen
Hunter McMillen

Reputation: 61515

No it is not possible with Java Reflection. Things like local variable names are usually removed by the compiler to provide some obfuscation and to optimize space. There is a byte code library ASM which can inspect the state of things at runtime, which may be useful to you.

Upvotes: 6

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

You can get access to local variable map using bytecode reverse engineering libraries like ASM. Note however that the name of local variables might not always be present in the bytecode, but the number and types will always be there.

There is no way to obtain this information via reflection. Reflection works on method level, while local variables are on code block level.

Upvotes: 3

NPE
NPE

Reputation: 500167

In a word, you can't. The names of local variables are not preserved by the compiler.

As a quick experiment, I have compiled the following class using Java 6 and default compiler options:

public class X {
  public static void main(String[] args) {
    int var = 2;
    System.out.println(var);
  }
}

A quick examination of the resulting .class file reveals that the name of the local variable (var) didn't make it there.

Upvotes: 9

Maurício Linhares
Maurício Linhares

Reputation: 40313

If my local variables you mean instance variables and class variables, here's how you would go:

String s = new String("This is a sample");
Class<String> type = s.getClass();
for ( Field f : type.getFields() ) {
    System.out.printf("Field %s is of type %s%n", f.getName(), f.getType().getName());
}

If what you mean is variables local to methods/constructors, you can not access them with reflection.

Upvotes: 3

Related Questions