java - 有没有办法在另一个类的 hibernate validator 中获取约束的声明值?

标签 java reflection hibernate-validator

使用 hibernate validator 我声明了这样的东西

public class TestSomething{

    @Length(max=30, message="Error Message.")
    private String name;

    getter and setter here
 }

在这种情况下是否可以获得最大字符数 30 类似

   TestSomething ts = new TestSomething();
   int maxValue =  ts.getName.getThatMaximumNumberOrSomethng

java会不会对这种情况进行反射(reflection)?

最佳答案

您应该使用 Bean Validation 元数据 API。如果你有一个 Validator 实例,你可以得到一个所谓的 ConstraintDescriptor:

BeanDescriptor beanDescriptor = getBeanDescriptor( TestSomething.class );
PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty( "name" );
Set<ConstraintDescriptor<?>> constraintDescriptors = propertyDescriptor.getConstraintDescriptors();

一旦你有了正确的ConstraintDescriptor,你就可以调用

constraintDescriptor.getAnnotation(); // to get the actual constraint annotation
constraintDescriptor.getAttributes().get("max"); // to retrieve the attribute from the attributes map provided by the descriptor as convenience

关于java - 有没有办法在另一个类的 hibernate validator 中获取约束的声明值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28523703/

相关文章:

java - 断言 java 中私有(private)方法抛出异常的另一种方法

java - 为标准 bean 验证注释注册新的约束 validator

spring-data-jpa - JPA、Hibernate 验证器 - 电子邮件验证器不适用于 String

java - 检查 Java 中的三角形类型

java - Apache FOP 能否用于生成可防止 PDF 客户端缩放和改变方向的 PDF?

ruby - 是否有可能获得 Ruby 中的所有特征类?

php - PHP 中的模拟 exit() 函数

hibernate - 使用 Hibernate 验证,我可以查询正在验证的实体吗?

java - 了解主机卡模拟和 APDU 背后的代码

java - 如何在 Spring 中使用注释定义 PasswordEncoder?