我们正在开发一个仅在我们的源代码中删除javax.persistence.GeneratedValue注释后才能正常运行的工具(用于内部使用)(我们在工具中设置Id,由于GeneratedValue注释而被拒绝)...但是对于正常操作,我们需要这个注释。
如何在运行时删除Java注释(可能使用Reflection)?
这是我的类:
如果您可以从一个字段获取注释映射表,那么同样的解决方案也适用。
如何在运行时删除Java注释(可能使用Reflection)?
这是我的类:
@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());
如果您可以从一个字段获取注释映射表,那么同样的解决方案也适用。