gpt4 book ai didi

java - 将动态参数传递给注释

转载 作者:行者123 更新时间:2023-11-30 04:23:26 24 4
gpt4 key购买 nike

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

我知道注释不是设计来修改的,但我正在使用 Hibernate Filters在我的例子中,要设置的条件不是静态的。

我认为唯一的解决方案是使用旨在读取和修改字节码的库,例如 Javassist 或 ASM但如果有其他解决方案那就更好了。

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

提前致谢

最佳答案

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

  • 创建一个注释,用于接收实现验证规则的类
  • 创建一个注解可以接收的接口(interface)
  • 为具有规则逻辑的接口(interface)创建一个实现
  • 将注释添加到您的模型类
  • 创建一个注释处理器,对每个带注释的字段应用验证

我用 Groovy 编写了以下示例,但使用了标准 Java 库和惯用的 Java。如果有任何内容不可读,请警告我:

import java.lang.annotation.*

// Our Rule interface
interface Rule<T> { boolean isValid(T t) }

// Here is the annotation which can receive a Rule class
@Retention(RetentionPolicy.RUNTIME)
@interface Validation { Class<? extends Rule> value() }

// An implementation of our Rule, in this case, for a Person's name
class NameRule implements Rule<Person> {
PersonDAO dao = new PersonDAO()
boolean isValid(Person person) {
Integer mode = dao.getNameValidationMode()
if (mode == 1) { // Don't hardcode numbers; use enums
return person.name ==~ "[A-Z]{1}[a-z ]{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 ,它提供了一些有趣的通过注释进行验证的模型。

关于java - 将动态参数传递给注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16423571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com