javassist简介
Javassist是一个开源的分析、编辑和创建Java字节码的类库。
demo目的给一个字节码里面的构造方法添加一个输出语句
- 待添加的java类
package com.suse.yuxin;
public class User {
private String userName;
private String userNumber;
public User(String userName, String userNumber) {
super();
this.userName = userName;
this.userNumber = userNumber;
}
}
- 测试代码
public class TestAssist {
public static void main(String args[]) throws NotFoundException, CannotCompileException, IOException{
ClassPool pool = ClassPool.getDefault();
//设置classPath
pool.appendClassPath("D:\\javaworkspace\\Test\\bin");
//获取一个class文件
CtClass ctClass = pool.get("com.suse.yuxin.User");
//获取构造方法
CtConstructor ctConstructor = ctClass.getConstructors()[0];
//插入输出语句
ctConstructor.insertAfter("System.out.println();");
ctClass.writeFile("D:\\javaworkspace\\Test\\bin\\output");
System.out.println("OK");
}
}
-
反编译查看
工具
- javassist jar 包使用的是3.9.0
- 反编译使用的工具是 jd-gui
Nothing is certain in this life. The only thing i know for sure is that. I love you and my life. That is the only thing i know. have a good day