addCatch example

官方文档

addCatch() inserts a code fragment into a method body so that the code fragment is executed when the method body throws an exception and the control returns to the caller. In the source text representing the inserted code fragment, the exception value is referred to with the special variable $e.

For example, this program:

CtMethod m = ...;
CtClass etype = ClassPool.getDefault().get("java.io.IOException");
m.addCatch("{ System.out.println($e); throw $e; }", etype);
translates the method body represented by m into something like this:

try {
    the original method body
}
catch (java.io.IOException e) {
    System.out.println(e);
    throw e;
}
Note that the inserted code fragment must end with a throw or return statement.

例子

public static void main(String[] args) throws Exception{
        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.makeClass("com.kq.javassist.service.impl.RegisterServiceImpl");

        CtMethod registerMethod = CtNewMethod.make("public void register(String username,String password) {};", cc);
        cc.addMethod(registerMethod);

        registerMethod.setBody("{ System.out.println($1); System.out.println($2); }");

        CtClass etype = ClassPool.getDefault().get("java.lang.Exception");
        registerMethod.addCatch("{ System.out.println($e); throw $e; }", etype);


        cc.writeFile("D:\\javassist\\");
    }

 生成类


import java.io.PrintStream;

public class RegisterServiceImpl
{
  public void register(String paramString1, String paramString2)
  {
    try
    {
      System.out.println(paramString1);
      System.out.println(paramString2);
      return;
    }
    catch (Exception localException)
    {
      System.out.println(localException);
      throw localException;
    }
  }
}

猜你喜欢

转载自blog.csdn.net/kq1983/article/details/90144557