【发布时间】:2016-07-21 13:50:38
【问题描述】:
我们正在构建一个工具(供内部使用),该工具仅在从我们的源代码中删除 javax.persistence.GeneratedValue 注释时才有效(我们正在工具中设置 Id,由于 GeneratedValue 注释而被拒绝)。 .. 但是对于正常操作,我们需要这个注释。
如何在运行时删除 Java 注释(可能使用反射)?
这是我的课:
@Entity
public class PersistentClass{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
// ... Other data
}
这是我希望能够在运行时将其更改为:
@Entity
public class PersistentClass{
@Id
private long id;
// ... Other data
}
可以在类本身上执行此操作:
// for some reason this for-loop is required or an Exception is thrown
for (Annotation annotation : PersistentClass.class.getAnnotations()) {
System.out.println("Annotation: " + annotation);
}
Field field = Class.class.getDeclaredField("annotations");
field.setAccessible(true);
Map<Class<? extends Annotation>, Annotation> annotations = (Map<Class<? extends Annotation>, Annotation>) field.get(PersistentClass.class);
System.out.println("Annotations size: " + annotations.size());
annotations.remove(Entity.class);
System.out.println("Annotations size: " + annotations.size());
如果您可以从字段中获取注释映射,那么同样的解决方案将适用。
【问题讨论】:
-
我认为,更好的问题是询问如何使该工具与存在的注释一起工作。
-
您能找到解决方案吗?我也在寻找类似的解决方案。
标签: java reflection