日期:2014-05-20  浏览次数:20669 次

求大神路过,java运行过程中能否修改注解(Annotation)内容?如果能,请问怎么修改
public class ListBean {
    @XmlElements({
        @XmlElement(name = "bean", type = AccountBean.class)
    })
    public List getList() {
        return list;
    }
}
类似我有这样一个类,我在程序运行过程中需要修改XmlElement注解中的type属性。

请问这个功能能否实现,如果能实现,请问怎么实现。

能有代码表示最好
------最佳解决方案--------------------
可以用javassist

讀:
import javassist.bytecode.annotation.Annotation;
    :
 CtMethod m = ... ;
 MethodInfo minfo = m.getMethodInfo();
 AnnotationsAttribute attr = (AnnotationsAttribute)
         minfo.getAttribute(AnnotationsAttribute.invisibleTag);
 Annotation an = attr.getAnnotation("Author");
 String s = ((StringMemberValue)an.getMemberValue("name")).getValue();
 System.out.println("@Author(name=" + s + ")");

寫:
ClassFile cf = ... ;
 ConstPool cp = cf.getConstPool();
 AnnotationsAttribute attr
     = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
 Annotation a = new Annotation("Author", cp);
 a.addMemberValue("name", new StringMemberValue("Chiba", cp));
 attr.setAnnotation(a);
 cf.addAttribute(attr);
 cf.setVersionToJava5();

http://www.csg.is.titech.ac.jp/~chiba/javassist/html/javassist/bytecode/AnnotationsAttribute.html
 
------其他解决方案--------------------
额,真的可以,谢谢大神提供的帮助!
------其他解决方案--------------------
sssf好的,看不到
------其他解决方案--------------------
我也想改注解,看看有没有什么方法
------其他解决方案--------------------
问题虽然解决了,但是在项目中的实用性不大,因为就算即时修改了注解,虚拟机也不能即时编译。最后还是换了一种方法,最后非常感谢 dracularking 提供的帮助,这种解决方式让我对javassist 有了更深刻的了解