我們正在構建一個工具(僅供內部使用),它只有在從我們的源代碼中刪除了javax.persistence.GeneratedValue註釋(我們在工具中設置Id,並且由於GeneratedValue註釋而被拒絕)時纔會生效。但對於正常的操作,我們需要這個註釋。如何在運行時刪除Java註釋(可能使用反射)?
如何在運行時刪除Java註釋(可能使用反射)?
這是我的課:
@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());
如果您可以從字段中獲取註釋映射,那麼將應用相同的解決方案。
更好問題在於如何讓這個工具能夠在註釋中出現,我想。 – SpaceTrucker