将动态参数传递给注释

我想知道是否有可能将动态值传递给注释属性。

我知道注释不是为了修改而设计的,但是我使用的是Hibernatefilter,并且在我的情况下,条件不是静态的。

我认为唯一的解决方案是使用librairies,其目的是读取和修改字节代码,如Javassist或ASM,但如果有另一个解决方案,它会好得多。

ps:在我的情况下的困难是我应该修改注释(属性的值),但我上面提到的librairies允许创建不编辑这就是为什么我想知道另一个解决方案

提前致谢

我不知道它是否与您的框架很好地集成,但我想建议以下内容:

  • 创建一个注释,该注释接收实现validation规则的Class
  • 创建注释可以接收的接口
  • 为具有规则逻辑的接口创建实现
  • 将注释添加到模型类
  • 创建一个注释处理器,为每个带注释的字段应用validation

我在Groovy中编写了以下示例,但使用的是标准Java库和惯用Java。 如果有什么不可读的话,请警告我:

 import java.lang.annotation.* // Our Rule interface interface Rule { boolean isValid(T t) } // Here is the annotation which can receive a Rule class @Retention(RetentionPolicy.RUNTIME) @interface Validation { Class value() } // An implementation of our Rule, in this case, for a Person's name class NameRule implements Rule { PersonDAO dao = new PersonDAO() boolean isValid(Person person) { Integer mode = dao.getNameValidationMode() if (mode == 1) { // Don't hardcode numbers; use enums return person.name ==~ "[AZ]{1}[az ]{2,25}" // regex matching } else if (mode == 2) { return person.name ==~ "[a-zA-Z]{1,25}" } } } 

在这些声明之后,用法:

 // Our model with an annotated field class Person { @Validation(NameRule.class) String name } // Here we are mocking a database select to get the rule save in the database // Don't use hardcoded numbers, stick to a enum or anything else class PersonDAO { Integer getNameValidationMode() { return 1 } } 

注释的处理:

 // Here we get each annotation and process it against the object class AnnotationProcessor { String validate(Person person) { def annotatedFields = person.class.declaredFields.findAll { it.annotations.size() > 0 } for (field in annotatedFields) { for (annotation in field.annotations) { Rule rule = annotation.value().newInstance() if (! rule.isValid(person)) { return "Error: name is not valid" } else { return "Valid" } } } } } 

并测试:

 // These two must pass assert new AnnotationProcessor().validate( new Person(name: "spongebob squarepants") ) == "Error: name is not valid" assert new AnnotationProcessor().validate( new Person(name: "John doe") ) == "Valid" 

另外,看看GContracts ,它提供了一些有趣的validation – 通过注释模型。

注释参数是类文件中的硬编码常量。 因此,更改它们的唯一方法是生成一个新的类文件。

不幸的是,我不熟悉Hibernate,因此我无法建议您在特定情况下的最佳选择。