写在前面
本文看下如何增加try catch异常捕获。
1:程序
- 需要增强的类:
public class ApiTest1 {public Integer strToInt(String str01, String str02) {return Integer.parseInt(str01);}}
- 插桩类
package com.dahuyou.javassist.huohuo.aa;import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.bytecode.AccessFlag;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.function.LongConsumer;public class MyDoIt extends ClassLoader {public static void main(String[] args) throws Exception {ClassPool pool = ClassPool.getDefault();// 获取类和方法CtClass ctClass = pool.get(ApiTest1.class.getName());ctClass.replaceClassName("ApiTest1", "ApiTest12");String clazzName = ctClass.getName();CtMethod ctMethod = ctClass.getDeclaredMethod("strToInt");// 方法信息:methodInfo.getDescriptor();MethodInfo methodInfo = ctMethod.getMethodInfo();ctMethod.addCatch("{ com.dahuyou.javassist.huohuo.aa.MyDoIt.showErr($e); throw $e; }", ClassPool.getDefault().get("java.lang.Exception")); // 添加异常捕获ctClass.writeFile();// 测试调用byte[] bytes = ctClass.toBytecode();Class<?> clazzNew = new MyDoIt().defineClass("com.dahuyou.javassist.huohuo.aa.ApiTest1", bytes, 0, bytes.length);// 反射运行测试Class aClass = clazzNew;Object obj = aClass.newInstance();Method main = aClass.getDeclaredMethod("strToInt", String.class, String.class);main.invoke(obj, "aa", "87");// System.out.println("执行耗时:" + (System.nanoTime() - startTime));}public static void showErr(Exception e) {System.out.println("错误了:" + e);}// private static void show(Object param) {public static void show(Integer param) {System.out.println("返回值:" + param);}
}
生成的字节码:
public Integer strToInt(String str01, String str02) {try {return Integer.parseInt(str01);} catch (Exception var4) {MyDoIt.showErr(var4);throw var4;}
}
运行: