如何在运行时删除Java Annotation(可能使用Reflection)?

Hea*_*vyE 6 java reflection

我们正在构建一个工具(供内部使用),只有在从我们的源代码中删除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)

如果您可以从字段中获取注释图,则应用相同的解决方案.

Joo*_*gen 0

创建一个新库,复制并过滤实体源以删除注释。这既不难也不不干净。

您还可以尝试自己进行类加载器和字节码操作。但类加载是一个污水坑。