We create a tool (for internal use) that only works if the javax.persistence.GeneratedValue annotation is removed from our source code (we set the Id in the tool, which is rejected due to the GeneratedValue annotation) ... but for normal operations we require this annotation.
How to remove Java annotation in Runtime (possibly using Reflection)?
This is my class:
@Entity
public class PersistentClass{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
}
This is what I would like to change at runtime:
@Entity
public class PersistentClass{
@Id
private long id;
}
This can be done in the class itself:
// 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());
If you can get the annotation map from the field, then the same solution will apply.
source
share