How to remove Java annotation in Runtime (possibly using Reflection)?

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;

  // ... Other data
}

This is what I would like to change at runtime:

@Entity
public class PersistentClass{
  @Id
  private long id;

  // ... Other data
}

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.

+4
source share
2 answers

You cannot delete annotation at runtime. Reflection only validates the code.

What can you do:

  • , ( ).
  • , . , ; .

, , Perl SED. , , , , .

, (PTS). , () "" , () .

PTS :

  if you see *this* pattern, replace it by *that* pattern

(, Java).

( PTS). ( PTS) :

 rule remove_Generated_value(a: annotations, e: expression):
          annotations -> annotations =
      " \a @GeneratedValue(strategy = \e) " -> " \a ";

: " , GeneratedValue " " ", () ". [ , , , .] (" , langauge Java .)

+1

, . .

ClassLoader -. - .

-1

Source: https://habr.com/ru/post/1648658/


All Articles