开发者

Modifying annotation attribute value at runtime in java

开发者 https://www.devze.com 2023-01-04 07:12 出处:网络
some methods in our model pojos have been annotated like this: @Column(name=\"cli_clipping_id\", updatable=false, columnDefinition = \"varchar(\" + ModelUtils.ID_LENGTH + \") COLLATE utf8_bin\")

some methods in our model pojos have been annotated like this:

@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:

[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
  • Create a copy of the column annotation, setting columnDefinition null using javaassist.
  • 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. 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.


If you are building with ANT, you could do a precompile step and use a regex to change the code in the files.


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.

I am still curious how to get it done for methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消