简体   繁体   English

在java中运行时修改注释属性值

[英]Modifying annotation attribute value at runtime in java

some methods in our model pojos have been annotated like this: 我们的模型pojos中的一些方法已经注释如下:

@Column(name="cli_clipping_id", updatable=false, columnDefinition = "varchar(" + ModelUtils.ID_LENGTH + ") COLLATE utf8_bin")

columnDefinition attribute is database vendor dependant, so when trying to drop schema in HSQLDB using Hibernate it fails: columnDefinition属性是依赖于数据库供应商的,因此当尝试使用Hibernate在HSQLDB中删除模式时,它会失败:

[ERROR] 16 jun 12:58:42.480 PM main [org.hibernate.tool.hbm2ddl.SchemaExport]
Unexpected token: COLLATE in statement [create table cms.edi_editorial_obj (edi_uuid varchar(23) COLLATE] 

To fix this, i'm thinking on this solution (but don't want to spend time if it isn't possible) , at runtime, for each method column annotated: 为了解决这个问题,我正在考虑这个解决方案(但不想花时间,如果不可能),在运行时,为每个注释的方法列:

  • Get @Column annotation 获取@Column注释
  • Create a copy of the column annotation, setting columnDefinition null using javaassist. 创建列注释的副本,使用javaassist设置columnDefinition null。
  • set column method annotation to the copy column annotation object overriding the old one (i don't know it this is possible) 将列方法注释设置为复制列注释对象覆盖旧的注释对象(我不知道这是可能的)

Is it possible to "hack" these methods this way? 是否有可能以这种方式“破解”这些方法?

Any help would be much appreciated ... 任何帮助将非常感激 ...

I don't think the method you suggest is possible because: 我不认为你建议的方法是可行的,因为:

  1. The annotation value which you get at runtime is actually a proxy class implementing the annotation interface. 您在运行时get的注释值实际上是实现注释接口的代理类。 You can't set new values to its attributes. 您无法为其属性设置新值。
  2. It is not possible to set new annotation values to the classes or methods at runtime. 在运行时无法为类或方法设置新的注释值。

However, you can move to a xml based configuration for Hibernate where you can modify the parameter from outside the code. 但是,您可以转到基于xml的Hibernate配置,您可以在其中修改代码外部的参数。

如果使用ANT构建,则可以执行预编译步骤并使用正则表达式更改文件中的代码。

Though, this is in fact an old thread the Answer two above is incorrect for point 2: actually class anotations can be changed while runtime. 虽然,这实际上是一个旧线程,上面的答案2对于第2点是不正确的:实际上类运行可以在运行时更改。

I am still curious how to get it done for methods. 我仍然很好奇如何为方法完成它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM