我们正在构建一个工具(供内部使用),只有在从我们的源代码中删除javax.persistence.GeneratedValue注释时才会起作用(我们在工具中设置Id,由于GeneratedValue注释而被拒绝)......但是对于正常操作,我们需要这个注释.
如何在运行时删除Java Annotation(可能使用Reflection)?
这是我的班级:
@Entity
public class PersistentClass{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
// ... Other data
}
Run Code Online (Sandbox Code Playgroud)
这是我希望能够在运行时将其更改为:
@Entity
public class PersistentClass{
@Id
private long id;
// ... Other data
}
Run Code Online (Sandbox Code Playgroud)
可以在类本身上执行此操作:
// 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());
Run Code Online (Sandbox Code Playgroud)
如果您可以从字段中获取注释图,则应用相同的解决方案.
| 归档时间: |
|
| 查看次数: |
3712 次 |
| 最近记录: |