如何打印没有方法如果找不到则找到

时间:2015-09-17 20:53:54

标签: java javassist

我有这个代码我需要打印没有找到方法,如果没有找到方法怎么做。

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

} }

1 个答案:

答案 0 :(得分:0)

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