开发者

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

I need to know the type of 开发者_如何学Pythonthe 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?


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.


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜