image.png
package com.kang.javasis;
import javassist.*;
import java.io.IOException;
/**
* @author klr
* @create 2020-09-25-10:07
*/
public class Test {
public static void main(String[] args) throws CannotCompileException, NotFoundException, IOException {
ClassPool pool = ClassPool.getDefault();
//创建类
CtClass ctClass = pool.makeClass("com.kang.mybatis.proxy.User");
//创建属性
CtField f1 = CtField.make("private int num;", ctClass);
CtField f2 = CtField.make("private String test;", ctClass);
ctClass.addField(f1);
ctClass.addField(f2);
//创建方法
CtMethod setName = CtMethod.make("public void setName(String test){this.test=test;}", ctClass);
CtMethod getName = CtMethod.make("public String getName(){return test;}", ctClass);
ctClass.addMethod(setName);
ctClass.addMethod(getName);
CtConstructor ctConstructor = new CtConstructor(new CtClass[]{CtClass.intType, pool.get("java.lang.String")}, ctClass);
ctConstructor.setBody("{this.num=$1;this.test=$2;}");
ctClass.addConstructor(ctConstructor);
ctClass.writeFile("C:/nettyy/src/main/java/com/kang/javasis");
System.out.println("生成成功");
}
}
网友评论