Is there a way to identify the variables used in a Java method?

Is there a way to define variables used with a specific Java method?

For example, if I have the following method:

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

      

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

+3


source to share


2 answers


You can only do this if you are processing the generated bytecode. You can use a bytecode technical library like ASM, Javassist, etc.

Since, as far as I understand, your example uses an object field, here's the sample code uses Javassist and prints all the fields used by the methods of the given class:



ClassFile cf = new ClassFile(new DataInputStream(className + ".class")));
for (Object m : cf.getMethods()) {
    MethodInfo minfo = (MethodInfo)m;
    CodeAttribute ca = minfo.getCodeAttribute();
    for (CodeIterator ci = ca.iterator(); ci.hasNext();) {
        int index = ci.next();
        int op = ci.byteAt(index);
        if (op == Opcode.GETYFIELD) {
                    int a1 = ci.s16bitAt(index + 1);
                    String fieldName = " " + cf.getConstPool().getFieldrefName(a1); 
            System.out.println("field name: " + fieldName);
        }
    }

      

}

+4


source


It depends on whether the compile-time debug feature is enabled. If not, it discards the variable names and they are simply referenced by their stack address. You usually provide the compiler with the "-g" option to do this, but if you are using maven check its documentation to make sure it is enabled.

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();

      



From there LocalVariableTable has many methods for getting a list of local variables (see bcel documentation).

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

+4


source







All Articles