如何查找方法中调用的所有方法? [英] how to find all methods called in a method?

查看:196
本文介绍了如何查找方法中调用的所有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取在特定方法中调用的其他类的方法?

how to take the methods of other classes invoked in a specific 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;
}

getItem1()是:


  1. String.getBytes()

  2. String.getBytes(String)

  3. PrintStream.println / code>

  4. Integer.parseInt(String)

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


推荐答案

我会用 javassist

因此,假设您在类路径中有以下类可以访问,并希望查找从 getItem1()调用的所有方法:

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;
  }
}


创建另一个使用javassist api的类:

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

MethodFinder运行的输出是:

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   

这篇关于如何查找方法中调用的所有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆