标签:date desc sse lang 记录 pid addm efi demo
通过javassit操作类,是各种链路追踪系统最基本的知识。通过java agent机制实现代码不侵入的监控性能,实现主动监控,主动告警,代码时间消耗记录等等...
ClassPool:map结构 key为类名 value为CtClass
CtClass:拿到对应的操作类对象
CtField:构造类字段
CtMethod:操作方法,能赋到CtClass上 成为一个新方法
CtConstructor:操作构造方法 赋值到CtClass 成为一个新的构造方法
ClassPool pool = ClassPool.getDefault();
CtClass ctClass = pool.makeClass("demo.generate.GenerateHello");
// 构造接口
ctClass.setInterfaces(new CtClass[]{pool.makeInterface("java.lang.Cloneable")});
// 构造字段
CtField ctField = new CtField(CtClass.intType, "id", ctClass);
ctField.setModifiers(AccessFlag.PUBLIC);
// 类上增加字段
ctClass.addField(ctField);
// 增加构造函数
CtConstructor constructor = CtNewConstructor.make("public GenerateHello(int pid) {this.id=pid;}", ctClass);
ctClass.addConstructor(constructor);
// 增加方法
CtMethod ctMethod = CtNewMethod.make("public void hello(String desc){System.out.println(desc);}", ctClass);
ctClass.addMethod(ctMethod);
ctClass.writeFile();
Field[] fields = ctClass.toClass().getFields();
System.out.println("属性名称: " + fields[0].getName() + "属性类型: " + fields[0].getType());
生成对应的class文件,通过idea进入查看
package demo.generate;
public class GenerateHello implements Cloneable {
public int id;
public GenerateHello(int var1) {
this.id = var1;
}
public void hello(String var1) {
System.out.println(var1);
}
}
Point
package demo.extend;
/**
* @author chenhao.ych
* @date 2019-07-15
*/
public class Point {
private int x;
private int y;
public Point() {
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void move(int dx, int dy) {
this.x += dx;
this.y += dy;
}
}
修改文件
public static void main(String[] args) throws NotFoundException, CannotCompileException, IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
ClassPool classPool = ClassPool.getDefault();
CtClass ctClass = classPool.get("demo.extend.Point");
CtMethod method = ctClass.getDeclaredMethod("move");
method.insertBefore("{System.out.print(\"dx:\" + $1);System.out.println(\"dy: \" + $2);}");
method.insertAfter("{System.out.println(this.x);System.out.println(this.y);}");
ctClass.writeFile();
Class clazz = ctClass.toClass();
Method move = clazz.getMethod("move", new Class[]{int.class, int.class});
Constructor constructor = clazz.getConstructor(new Class[]{int.class, int.class});
move.invoke(constructor.newInstance(1, 2), 1, 2);
}
修改后的class文件反编译
package demo.extend;
public class Point {
private int x;
private int y;
public Point() {
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void move(int dx, int dy) {
System.out.print("dx:" + dx);
System.out.println("dy: " + dy);
this.x += dx;
this.y += dy;
Object var4 = null;
System.out.println(this.x);
System.out.println(this.y);
}
}
标签:date desc sse lang 记录 pid addm efi demo
原文地址:https://www.cnblogs.com/adroit/p/11192491.html