在java中运行时修改注释属性值 [英] Modifying annotation attribute value at runtime in java

查看:238
本文介绍了在java中运行时修改注释属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

columnDefinition 属性依赖于数据库供应商,因此当试图使用Hibernate在HSQLDB中删除模式时,它失败:

  [ ERROR] 16 jun 12:58:42.480 PM main [org.hibernate.tool.hbm2ddl.SchemaExport] 
意外的标记:语句中的COLLATE [create table cms.edi_editorial_obj(edi_uuid varchar(23)COLLATE]

为了解决这个问题,我在考虑这个解决方案(但不想花费时间,如果它不是可能),在运行时,为每个方法列注释:


  • 获取@Column注解

  • 创建列注释的副本,使用javaassist设置columnDefinition null。

  • 将列方法注释设置为co py列注释对象重写旧的(我不知道这是可能的)



是否有可能破解这些这样的方法吗?



任何帮助将不胜感激...

解决方案

我不认为你建议的方法是可行的,因为:


  1. 的注释值得到运行时的实际上是一个实现注释接口的代理类。您无法为其属性设置新值。

  2. 无法在运行时为类或方法设置新的批注值。

但是,您可以转移到基于xml的Hibernate配置,您可以从代码外部修改参数。


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.

这篇关于在java中运行时修改注释属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆