有没有办法识别在 Java 方法中使用的变量? [英] Is there a way to identify the variables being used within a Java method?

查看:20
本文介绍了有没有办法识别在 Java 方法中使用的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法确定特定 Java 方法正在使用的变量?

Is there a way to be able to determine the variables being used with a specific Java method?

例如,如果我有以下方法:

For example, if I have the following method:

public void getResult(){
   int result = value1 + value2;
}

然后我需要一个包含名称 result、value1 和 value2 的列表.

Then I need a list containing the names result, value1 and value2.

推荐答案

这取决于编译时是否启用了调试信息.如果不是,它会丢弃变量名,并且它们只是通过它们的堆栈地址引用来引用.通常,您会为编译器提供-g"选项来执行此操作,但如果您使用的是 maven,请查看其文档以了解如何确保已启用它.

It depends on whether you have debug information enabled when you compile. If not, it discards variable names, and they are simply referenced by their stack address reference. Typically you give the compiler the "-g" option to do this, but if you're using maven, check it's documentation to see how to make sure it's enabled.

如果启用了调试,您可以使用像 BCEL 这样​​的库来查找此信息:

If debug is enabled, you can use a library like BCEL to find out this information:

java.lang.reflect.Method javaMethod = ...; // lookup the actual method using reflection
org.apache.bcel.classfile.JavaClassjc = org.apache.bcel.Repository.lookupClass(classname);
org.apache.bcel.classfile.Method method = jc.getMethod(javaMethod);
org.apache.bcel.classfile.LocalVariableTable lvt = method.getLocalVariableTable();

从那里开始,LocalVariableTable 有很多方法来获取局部变量列表(请参阅 bcel 文档).

From there, the LocalVariableTable has plenty of method to get the list of local variables (see the bcel documentation).

有几个包可以做到这一点,但我首先想到的是 BCEL 和 Javassist.

There are several packages that can do this, but BCEL and Javassist come to mind off the top of my head.

这篇关于有没有办法识别在 Java 方法中使用的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆