问题描述
我正在尝试在Java 7中动态添加注释。但是这样做没有成功。可以使用一些帮助。
以下是我采取的两种方法。在这两种方法中,当我检查时添加新的注释后,类/字段都不会立即反映出来。
1。使用javaassist创建新的注释
public void javaassist(String className,List<String> props) throws Exception{
//pool creation
Classpool pool = Classpool.getDefault();
//extracting the class
CtClass cc = pool.getCtClass(className);
// create the annotation
ClassFile ccFile = cc.getClassFile();
ConstPool constpool = ccFile.getConstPool();
AnnotationsAttribute attr = new AnnotationsAttribute(constpool,AnnotationsAttribute.visibleTag);
for(String propName: props) {
javassist.bytecode.annotation.Annotation annot =
new javassist.bytecode.annotation.Annotation("org.hibernate.annotations.ColumnTransformer",constpool);
annot.addMemberValue("read",new StringMemberValue("aes_decrypt("+propName+",'mysecret')",ccFile.getConstPool()));
annot.addMemberValue("write",new StringMemberValue("aes_encrypt(?,ccFile.getConstPool()));
attr.addAnnotation(annot);
//looking for the method to apply the annotation on
CtField propField = cc.getDeclaredField(propName);
// add the annotation to the method descriptor
List<AnnotationsAttribute> atts= propField.getFieldInfo().getAttributes();
System.out.println(atts);
// propField.getFieldInfo().addAttribute(attr);
atts.add(attr);
System.out.println(atts);
}
}
2。使用Class.class.getDeclaredField(“ annotations”)
创建新的注释 @SuppressWarnings({ "unchecked","rawtypes" })
private void withNew(Class clazz,List<String> props) throws NoSuchFieldException,SecurityException,IllegalArgumentException,illegalaccessexception {
Field fieldAnnotations = Class.class.getDeclaredField("annotations");
fieldAnnotations.setAccessible(true);
Map<Class<? extends Annotation>,Annotation> annotations = (Map<Class<? extends Annotation>,Annotation>) fieldAnnotations.get(clazz);
for(String prop: props) {
annotations.put(ColumnTransformer.class,this.buildColTransfAnnotation(prop,key));
}
}
private Annotation buildColTransfAnnotation(final String propName,final String key) {
return new ColumnTransformer() {
@Override
public Class<? extends Annotation> annotationType() {
return ColumnTransformer.class;
}
@Override
public String write() {
return "aes_encrypt(?,'"+key+"')";
}
@Override
public String read() {
return "aes_decrypt("+propName+",'"+key+"')";
}
@Override
public String forColumn() {
return null;
}
};
}
以下是我的验证方式
private void print(List<String> props) throws NoSuchFieldException,SecurityException {
for(String propName: props) {
Field field = Partner.class.getDeclaredField(propName);
for(Annotation an: field.getAnnotations()) {
System.out.println(an);
}
}
}
似乎与Java 7有关。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)