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

查看:413
本文介绍了有没有办法识别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.

如果启用了debug,您可以使用像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天全站免登陆