java 怎么给注解传值_java – 将动态参数传递给注释

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

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

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

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

提前致谢

解决方法:

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

>创建一个注释,该注释接收实现验证规则的Class

>创建注释可以接收的界面

>为具有规则逻辑的接口创建实现

>将注释添加到模型类

>创建一个注释处理器,为每个带注释的字段应用验证

我在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 extends Rule> 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 ==~ "[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,它提供了一些有趣的验证 – 通过注释模型.

标签:javassist,java,annotations,bytecode,hibernate-filters

来源: https://codeday.me/bug/20191007/1867018.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值