随笔 - 581  文章 - 0 评论 - 48 阅读 - 131万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

第一步: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/

posted on   毛会懂  阅读(388)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示