Java字节码框架 -- Javassist
package com.carlzone.dubbo.javassist;
import javassist.*;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Modifier;
public class CompilerByJavassist {
public static void main(String[] args) throws Exception {
// ClassPool: CtClass对象容器
ClassPool pool = ClassPool.getDefault();
// 通过ClassPool生成一个public的User类
CtClass ctClass = pool.makeClass("");
// 添加属性
// 1. 添加属性private int id;
CtField idField = new CtField(pool.getCtClass("int"), "id", ctClass);
idField.setModifiers(Modifier.PRIVATE);
ctClass.addField(idField);
// 2.添加属性private String username
CtField nameField = new CtField(pool.get(""), "username", ctClass);
nameField.setModifiers(Modifier.PRIVATE);
ctClass.addField(nameField);
// 添加setter/getter方法
ctClass.addMethod(CtNewMethod.getter("getId", idField));
ctClass.addMethod(CtNewMethod.setter("setId", idField));
ctClass.addMethod(CtNewMethod.getter("getUsername", nameField));
ctClass.addMethod(CtNewMethod.setter("setUsername", nameField));
// 添加构造函数
CtConstructor ctConstructor = new CtConstructor(new CtClass[]{}, ctClass);
// 添加构造函数方法体
StringBuffer sb = new StringBuffer();
sb.append("{\n").append(" = 27;\n").append("=\"carl\";\n}");
ctConstructor.setBody(sb.toString());
ctClass.addConstructor(ctConstructor);
// 添加自定义方法
CtMethod printMethod = new CtMethod(CtClass.voidType, "print", new CtClass[]{}, ctClass);
printMethod.setModifiers(Modifier.PUBLIC);
StringBuffer printSb = new StringBuffer();
printSb.append("{\(\"begin!\");\n")
.append("(id);\n")
.append("(username);\n")
.append("(\"end!\");\n")
.append("}");
printMethod.setBody(printSb.toString());
ctClass.addMethod(printMethod);
// 生成一个Class
Class<?> clazz = ctClass.toClass();
Object obj = clazz.newInstance();
// 反射执行方法
obj.getClass().getMethod("print", new Class[]{}).invoke(obj, new Object[]{});
// 把生成的class写入到文件中
byte[] byteArr = ctClass.toBytecode();
FileOutputStream fos = new FileOutputStream(new File("D://"));
fos.write(byteArr);
fos.close();
}
}