Skip to main content
 首页 » 编程设计

java assist创建对象

2022年07月18日24qq78292959
第一步:maven添加jar (https://mvnrepository.com/artifact/org.javassist/javassist/3.28.0-GA)
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.28.0-GA</version>
</dependency>

第二步:
ppublic class TestAssist {
public static void main(String[] args) throws CannotCompileException, IOException, NotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException {
// 获取默认的类池
ClassPool pool = ClassPool.getDefault();

// 在类池设置类
CtClass cc = pool.makeClass("com.dong.assist.TestUser");

// 设置 类的属性
CtField name = CtField.make("private String name;",cc);
CtField age = CtField.make("private int age;",cc);

cc.addField(name);
cc.addField(age);

// 设置类的方法
CtMethod setAll = CtMethod.make("public void setName(String name,int age){"
+"this.name = name; this.age = age;}",cc);
CtMethod getName = CtMethod.make("public String getName(){" +
"return this.name;}",cc);
cc.addMethod(setAll);
cc.addMethod(getName);

// 设置类的构造器(两个参数)
CtConstructor constructor = new CtConstructor(new CtClass[]{pool.get("java.lang.String"),CtClass.intType},cc);
// 构造器体,里面的参数用$1,$2代替
constructor.setBody("{this.name = $1;this.age=$2;}");
cc.addConstructor(constructor);

// 保存
cc.writeFile("D:\\TestUser");
System.out.println("ok");

// 反射,创建对象
Class clazz = cc.toClass();
Constructor constructor1 = clazz.getConstructor(String.class, int.class);
constructor1.setAccessible(true);
Object obj = constructor1.newInstance(new Object[]{"hello",50});


Method getNameMethod = clazz.getDeclaredMethod("getName");
System.out.println(getNameMethod.invoke(obj));

Method setName = clazz.getDeclaredMethod("setName",String.class,int.class);
setName.invoke(obj,"maohuidong",30);
System.out.println(getNameMethod.invoke(obj));
}
}

第三步:github下载xjad,反编译生成的TestUser (https://github.com/aspeople/xjad)

参考:https://blog.csdn.net/mousebaby808/article/details/37696371

https://www.bbsmax.com/A/Gkz10Me2dR/


本文参考链接:https://www.cnblogs.com/maohuidong/p/14911989.html