how to find all methods called in a method?

前端 未结 1 1335
无人及你
无人及你 2020-12-01 15:33

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

EXAMPLE

method getItem1()

public String getItem1() t         


        
相关标签:
1条回答
  • 2020-12-01 16:00

    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   
    
    0 讨论(0)
提交回复
热议问题