• javaassist创建对象


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

  • 相关阅读:
    《代码大全2》阅读笔记03
    第一阶段意见评论
    大二下学期学习进度(十一)
    四叶草社交平台——十天冲刺(10)
    四叶草社交平台——十天冲刺(9)
    四叶草社交平台——十天冲刺(8)
    四叶草社交平台——十天冲刺(7)
    四叶草社交平台——十天冲刺(6)
    四叶草社交平台——十天冲刺(5)
    四叶草社交平台——十天冲刺(4)
  • 原文地址:https://www.cnblogs.com/maohuidong/p/14911989.html
Copyright © 2020-2023  润新知