Re: Accessing methods called from within methods
David Hovemeyer <[email protected]>
| Newsgroups | gmane.comp.jakarta.bcel.user |
|---|---|
| Message-ID | <[email protected]> |
Steve Sevik wrote:
>Hello,
>
>I'm a new user of BCEL. I am trying to get access to methods called from within methods. I tried all possible classes that I could think of, but in vain. Can somebody help me out please ?
>
>My Class 'myClass' has two methods A, B ; and the main method calls method A which in turn calls method B, I was able to get the main method and print its code using the following code:
>
>JavaClass clazz = Repository.lookupClass(myClass);
>Method[] methods = clazz.getMethods();
>for(int i=0; i < methods.length; i++){
> if("main".equals(methods[i].getName())){
> Code code = methods[i].getCode();
> System.out.println(code.toString());
> }
>}
>
>How can I get access to method A from within main ?
>I want to print out the fact that main calls method A.
>Then get access to method A's code from there and print out the fact that it calls method B.
>
>
import org.apache.bcel.Constants;
import org.apache.bcel.generic.*;
ClassGen classGen = new ClassGen(clazz);
MethodGen methodGen = new MethodGen(methods[i], clazz.getClassName(),
classGen.getConstantPool());
InstructionList il = methodGen.getInstructionList();
for (Iterator i = il.iterator(); i.hasNext(); ) {
InstructionHandle handle = (InstructionHandle) i.next();
if (handle.getInstruction() instanceof InvokeInstruction) {
InvokeInstruction invokeInstruction = (InvokeInstruction)
handle.getInstruction();
String calledClass =
invokeInstruction.getClassName(classGen.getConstantPool());
String calledMethodName =
invokeInstruction.getName(classGen.getConstantPool());
String calledMethodSignature =
invokeInstruction.getSignature(classGen.getConstantPool());
boolean isStaticMethod = invokeInstruction.getOpcode() ==
Constants.INVOKESTATIC;
// now you can check to see if the method called is the one you want
}
}
-Dave