public ExcelBean createExcelBean(String[] propertyArray, String[] typeArray, String[] columnNameArray) throws NotFoundException, CannotCompileException, InstantiationException, IllegalAccessException {
ExcelBean excelBean = null;
ClassPool pool = ClassPool.getDefault();
//在tomcat环境下,向pool插入一个类对象的搜索路径
pool.insertClassPath("com.camb.common.web.bean.ExcelBean");
//获取要修改的类
CtClass ctClass = pool.get("com.camb.common.web.bean.ExcelBean");
for (int i = 0; i < propertyArray.length; i++) {
//生成属性以及get和set方法
String property = propertyArray[i];
String method = property.substring(0, 1).toUpperCase() + property.substring(1, property.length());
String type = typeArray[i];
String column = columnNameArray[i];
ctClass.addField(CtField.make("private " + type + " " + property + ";", ctClass));
ctClass.addMethod(CtMethod.make("public void set" + method + "(" + type + " " + property + "){this." + property + " = " + property + ";}", ctClass));
ctClass.addMethod(CtMethod.make("public " + type + " get" + method + "(){return this." + property + ";}", ctClass));
//获取类里的属性
CtField ctField = ctClass.getField(property);
FieldInfo fieldInfo = ctField.getFieldInfo();
System.out.println("属性名:" + ctField.getName());
ConstPool cp = fieldInfo.getConstPool();
//获取注解信息
AnnotationsAttribute attribute = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
Annotation annotation = new Annotation("com.camb.common.web.util.Excel", cp);
//修改名称为name的注解
annotation.addMemberValue("name", new StringMemberValue(column, cp));
attribute.setAnnotation(annotation);
fieldInfo.addAttribute(attribute);
//打印修改后注解
Annotation annotation2 = attribute.getAnnotation("com.camb.common.web.util.Excel");
String value = ((StringMemberValue) annotation2.getMemberValue("name")).getValue();
System.out.println("修改后的注解参数===" + value);
}
//修改后的class
Class<?> c = ctClass.toClass();
excelBean = (ExcelBean) c.newInstance();
ctClass.detach();
return excelBean;
}
pool.insertClassPath("com.camb.common.web.bean.ExcelBean");这个设置并不能找到class的位置,如果使用pool.insertClassPath(new ClassClassPath(ExcelBean.class));虽然能找class,但是会产生异常
com.camb.common.web.exception.ProcessException: javassist.CannotCompileException: by java.lang.LinkageError: loader (instance of org/apache/catalina/loader/WebappClassLoader): attempted duplicate class definition for name: "com/camb/common/web/bean/ExcelBean"