【问题标题】:How to print no methods Found if none is found如果没有找到方法,如何打印没有找到的方法
【发布时间】:2015-09-17 20:53:53
【问题描述】:

我有这段代码,如果没有找到方法,我需要打印找不到方法。

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

} }

【问题讨论】:

  • 您是否尝试过阅读 Java 中的反射?
  • 你需要一个字节码库,比如Apache Commons BCEL™。
  • @YassinHH 不相关,因为反射要求类在类路径中,这里不是这样,它不能给你字节码指令。
  • @Andreas 好的,谢谢你的回答
  • 你也可以去研究Class File Format和JVM Instruction Set,自己编写一个解析器,不需要第三方库的帮助。但是,您如何“到处搜索”却一无所获,十几个库中的一个或文档都找不到,这是一个谜……

标签: java javassist


【解决方案1】:

Javassist 不允许您开箱即用地实现您的要求。但是您可以轻松地扩展 ExprEditor 的行为来实现它。

第一步是创建一个 ExprEditor 子类,我们称之为 ExprEditorMethodCallAware。您唯一需要知道的是,ExprEditor 的入口点称为 doit,您可以在 code 中轻松看到。

public class ExprEditorMethodCallAware extends ExprEditor {

    private boolean processedMethodCalls;

    public void setProcessedMethodCalls(boolean processedMethodCalls) {
        this.processedMethodCalls = processedMethodCalls;
    }

    public boolean isProcessedMethodCalls() {
        return this.processedMethodCalls;
    }

    @Override
    public boolean doit(CtClass arg0, MethodInfo arg1)
            throws CannotCompileException {
        processedMethodCalls = false;
        boolean doit = super.doit(arg0, arg1);
        return doit;
    }
}

现在通过这个小技巧,您可以将代码改写如下:

 /// ... your existing code

 // we create an instance using our base class instead of ExprEditor
 ExprEditorMethodCallAware exprEditor =    new ExprEditorMethodCallAware() {
    public void edit(MethodCall m)
                  throws CannotCompileException
    {
        // notice the set
        setProcessedMethodCalls(true);
        System.out.println(m.getClassName() + "." + m.getMethodName() + " " + m.getSignature());
    }
 };

// we now instrument the code as you were already doing it
method.instrument(exprEditor);

// And now you check if there were or not methodCalls processed 
if(!exprEditor.isProcessedMethodCalls()) {
   System.out.println("No methodCalls found in " + method.getMethodName());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 2013-10-30
    • 2014-08-27
    相关资源
    最近更新 更多