org.javassist
javassist
3.28.0-GA
public class Test {
public static final Map NEW_FIELD_MAP = new HashMap<>();
public static String toUpperCase4Index(String string) {
char[] methodName = string.toCharArray();
methodName[0] = toUpperCase(methodName[0]);
return String.valueOf(methodName);
}
public static Object test1() throws Exception {
ClassPool pool = ClassPool.getDefault();
//新建一个类
CtClass ctClass = pool.makeClass("com.example.bugcount.MyDailyReport");
CtConstructor cons = new CtConstructor(new CtClass[] {}, ctClass);
cons.setBody("{}");
//添加构造方法
ctClass.addConstructor(cons);
//创建字段
for(String fieldName: NEW_FIELD_MAP.keySet()) {
// 字段类型
String fieldType = NEW_FIELD_MAP.get(fieldName).getClass().getName();
// 创建新字段
CtField ctField = new CtField(pool.get(fieldType), fieldName, ctClass);
ctField.setModifiers(Modifier.PRIVATE);
ctClass.addField(ctField);
List attributeInfos = ctField.getFieldInfo().getAttributes();
AnnotationsAttribute annotationsAttribute = !attributeInfos.isEmpty()?(AnnotationsAttribute) attributeInfos.get(0):
new AnnotationsAttribute(ctField.getFieldInfo().getConstPool(), AnnotationsAttribute.visibleTag);
ConstPool fieldConstPool = ctField.getFieldInfo().getConstPool();
if(!"".equals(NEW_FIELD_MAP.get(fieldName))){
Annotation annotation = new Annotation("com.alibaba.excel.annotation.ExcelProperty", fieldConstPool);
StringMemberValue[] elements = {new StringMemberValue((String)NEW_FIELD_MAP.get(fieldName), fieldConstPool)};
ArrayMemberValue amv = new ArrayMemberValue(ctField.getFieldInfo().getConstPool());
amv.setValue(elements);
//添加注解的值
annotation.addMemberValue("value", amv);
annotationsAttribute.addAnnotation(annotation);
}else {
Annotation annotation = new Annotation("com.alibaba.excel.annotation.ExcelIgnore", fieldConstPool);
annotationsAttribute.addAnnotation(annotation);
}
ctField.getFieldInfo().addAttribute(annotationsAttribute);
//添加set get方法
ctClass.addMethod(CtNewMethod.setter( "set" + toUpperCase4Index(fieldName),ctField));
ctClass.addMethod(CtNewMethod.getter( "get" + toUpperCase4Index(fieldName),ctField));
}
//返回对象
return ctClass.toClass().newInstance();
}
public static void main(String[] args) throws Exception {
NEW_FIELD_MAP.put("test1","测试1");
NEW_FIELD_MAP.put("test2","");
NEW_FIELD_MAP.put("test3","测试3");
test1();
}
}