Search in sources :

Example 76 with CtField

use of javassist.CtField in project dq-easy-cloud by dq-open-cloud.

the class DynamicRuleTest method makeclass.

public static void makeclass(String className, String methodName, String fieldName, String interfaceCode) throws NotFoundException, CannotCompileException, IOException {
    ClassPool pool = ClassPool.getDefault();
    CtClass ct = pool.makeClass("com.test.bean.Emp");
    // 创建属性
    CtField e1 = CtField.make("public int no;", ct);
    CtField e2 = CtField.make("public String name;", ct);
    ct.addField(e1);
    ct.addField(e2);
    CtMethod m1 = CtMethod.make("public int getNo(){return no;}", ct);
    CtMethod m2 = CtMethod.make("public void setNo(int no){return this.no = no;}", ct);
    ct.addMethod(m1);
    ct.addMethod(m2);
    // 添加构造器
    CtConstructor constructor = new CtConstructor(new CtClass[] { CtClass.intType, pool.get("java.lang.String") }, // 构造器的参数
    ct);
    // 构造器的方法体
    constructor.setBody("{this.no = no; this.name=name;}");
    // 如果不添加构造器 则会生成一个空的构造器
    ct.addConstructor(constructor);
    // 将构造好的类写出来
    ct.writeFile("E:/JavaFile");
    System.out.println("类生成功");
}
Also used : CtClass(javassist.CtClass) CtField(javassist.CtField) ClassPool(javassist.ClassPool) CtMethod(javassist.CtMethod) CtConstructor(javassist.CtConstructor)

Aggregations

CtField (javassist.CtField)76 CtClass (javassist.CtClass)47 CtMethod (javassist.CtMethod)27 CannotCompileException (javassist.CannotCompileException)24 NotFoundException (javassist.NotFoundException)22 ClassPool (javassist.ClassPool)20 CtConstructor (javassist.CtConstructor)15 Test (org.junit.Test)12 ClassFile (javassist.bytecode.ClassFile)9 IOException (java.io.IOException)7 Method (java.lang.reflect.Method)7 ArrayList (java.util.ArrayList)6 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)5 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)4 ConstPool (javassist.bytecode.ConstPool)4 SMethod (org.bimserver.shared.meta.SMethod)4 SParameter (org.bimserver.shared.meta.SParameter)4 InsertableMethod (com.github.stephanenicolas.afterburner.inserts.InsertableMethod)3 SimpleInsertableMethod (com.github.stephanenicolas.afterburner.inserts.SimpleInsertableMethod)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3