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 voi
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.
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, the LocalVariableTable has plenty of method to get the list of local variables (see the bcel documentation).
There are several packages that can do this, but BCEL and Javassist come to mind off the top of my head.
You can do it only if you are parsing the generated byte code. You can use byte code engineering library, e.g ASM, Javassist etc.
Since as far as I understand your example uses the object field here is a code sample uses Javassist and prints all fields used by methods of 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);
}
}
}