Changing annotation attribute value at runtime in java

Some methods in our pojos model were annotated as follows:

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

The columnDefinition attribute is dependent on the database provider, so if you try to reset the schema in HSQLDB using Hibernate, this will not work:

 [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 think of this solution (but don't want to waste time if this is not possible) at runtime for each method column annotated:

  • Get @Column annotation
  • Create a copy of the column annotation by setting the columnDefinition null value using javaassist.
  • set the column method annotation to the copy column annotation object that overrides the old one (I don't know what is possible)

Is it possible to โ€œcrackโ€ these methods in this way?

Any help would be greatly appreciated ...

+4
source share
3 answers

I do not think that the method you proposed is possible, because:

  • The annotation value that you get at run time is actually a proxy class that implements the annotation interface. You cannot set new values โ€‹โ€‹in your attributes.
  • It is not possible to set new annotation values โ€‹โ€‹for classes or methods at run time.

However, you can go to the xml configuration for Hibernate, where you can change the parameter outside the code.

+3
source

If you build using ANT, you can take a precompilation step and use a regular expression to change the code in the files.

+1
source

Although this is actually an old thread, the answer โ€œTwo questions aboveโ€ is incorrect for point 2: In fact, cool annotations can be changed at runtime.

I'm still wondering how to do this for methods.

0
source

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


All Articles