JAVAssist---动态修改注解
来源:互联网 发布:阿里云客服是什么 编辑:程序博客网 时间:2024/06/04 18:40
先来看看我们需要修改注解的代码:
-
-
-
-
-
-
- public class CollectionBase<T> extends BaseEaoImpl<T> {
-
-
-
- @PersistenceContext(unitName="collection-entity")
- protected EntityManager em;
-
-
-
- @Override
- protected EntityManager getEntityManager() {
- return this.em;
- }
- }
需要修改的是unitName.
那么该如何修改呢?开始是没有任何思路的,但当时的我总有种感觉一定可以修改,所以就查了一下,发现了JAVAssist:开源的分析。编辑和创建java字节码的类库。更深入的认识可以百度了解一下,下面一个小的demo来修改一下注解:
首先来看是如何获得这个注解的:
- @Test
- public void ReadTest() throws NotFoundException{
- ClassPool pool = ClassPool.getDefault();
-
- CtClass ct = pool.get("com.tgb.itoo.collection.base.CollectionBase");
-
- CtMethod[] cms = ct.getDeclaredMethods();
-
- CtMethod cm = cms[0];
- System.out.println("方法名称====" + cm.getName());
-
- MethodInfo methodInfo = cm.getMethodInfo();
-
- CtField cf = ct.getField("em");
-
- FieldInfo fieldInfo = cf.getFieldInfo();
- System.out.println("属性名称===" + cf.getName());
-
-
- AnnotationsAttribute attribute = (AnnotationsAttribute) fieldInfo.getAttribute(AnnotationsAttribute.visibleTag);
- System.out.println(attribute);
-
- Annotation annotation = attribute.getAnnotation("javax.persistence.PersistenceContext");
- System.out.println(annotation);
-
- String text =((StringMemberValue) annotation.getMemberValue("unitName")).getValue() ;
- System.out.println("注解名称===" + text);
-
- }
运行结果:
- 方法名称====getEntityManager
- 属性名称===em
- @javax.persistence.PersistenceContext(unitName="collection-entity")
- @javax.persistence.PersistenceContext(unitName="collection-entity")
- 注解名称===collection-entity
修改注解的方法与获取的一样,只是需要为获取的注解赋值,代码如下:
- @Test
- public void UpdateTest() throws NotFoundException{
- ClassPool pool = ClassPool.getDefault();
-
- CtClass ct = pool.get("com.tgb.itoo.collection.base.CollectionBase");
-
-
- CtMethod[] cms = ct.getDeclaredMethods();
- CtMethod cm = cms[0];
- System.out.println("方法名称====" + cm.getName());
-
- MethodInfo minInfo = cm.getMethodInfo();
-
- CtField cf = ct.getField("em");
- FieldInfo fieldInfo = cf.getFieldInfo();
-
- System.out.println("属性名称===" + cf.getName());
-
- ConstPool cp = fieldInfo.getConstPool();
-
- AnnotationsAttribute attribute2 = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
- Annotation annotation = new Annotation("javax.persistence.PersistenceContext", cp);
-
-
- annotation.addMemberValue("unitName", new StringMemberValue("basic-entity", cp));
- attribute2.setAnnotation(annotation);
- minInfo.addAttribute(attribute2);
-
-
- Annotation annotation2 = attribute2.getAnnotation("javax.persistence.PersistenceContext");
- String text = ((StringMemberValue)annotation2.getMemberValue("unitName")).getValue();
-
- System.out.println("修改后的注解名称===" + text);
- }
运行结果:
- 方法名称====getEntityManager
- 属性名称===em
- 修改后的注解名称===basic-entity
多么神奇的动态修改注解,运行时修改很多问题就迎刃而解了!