how to find all methods called in a method?

霸气de小男生 提交于 2019-12-17 09:50:24

问题


how to take the methods of other classes invoked in a specific method?

EXAMPLE

method getItem1()

public String getItem1() throws UnsupportedEncodingException{
    String a = "2";
    a.getBytes();
    a.getBytes("we");
    System.out.println(a);
    int t = Integer.parseInt(a);
    return a;
}

The methods called in getItem1() are:

  1. String.getBytes()
  2. String.getBytes(String)
  3. PrintStream.println(String)
  4. Integer.parseInt(String)

回答1:


I would do this with javassist.

So let's say you have the following class accessible in your classpath and want to find all methods invoked from getItem1():

class MyClass {
  public String getItem1() throws UnsupportedEncodingException{
    String a = "2";
    a.getBytes();
    a.getBytes("we");
    System.out.println(a);
    int t = Integer.parseInt(a);
    return a;
  }
}

And you have this MyClass compiled. Create another class that uses javassist api:

public class MethodFinder {

  public static void main(String[] args) throws Throwable {
    ClassPool cp = ClassPool.getDefault();
    CtClass ctClass = cp.get("MyClass");
    CtMethod method = ctClass.getDeclaredMethod("getItem1");
    method.instrument(
        new ExprEditor() {
            public void edit(MethodCall m)
                          throws CannotCompileException
            {
                System.out.println(m.getClassName() + "." + m.getMethodName() + " " + m.getSignature());
            }
        });
  }
}

the output of the MethodFinder run is:

java.lang.String.getBytes ()[B   
java.lang.String.getBytes (Ljava/lang/String;)[B   
java.io.PrintStream.println (Ljava/lang/String;)V   
java.lang.Integer.parseInt (Ljava/lang/String;)I   


来源:https://stackoverflow.com/questions/13659042/how-to-find-all-methods-called-in-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!