如何访问注释属性中描述的字段 [英] How to access a field which is described in annotation property

查看:38
本文介绍了如何访问注释属性中描述的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以访问一个字段值,其中字段名称在注解中描述,注解类中的另一个字段.

Is it possible to access a field value, where field name is described in annotation which annotate another field in class.

例如:

@Entity
public class User {

    @NotBlank
    private String password;

    @Match(field = "password")
    private String passwordConfirmation;
}

注释:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = FieldMatchValidator.class)
@Documented
public @interface Match {

    String message() default "{}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String field();
}

现在,是否可以从 ConstraintValidator 实现类中的 User 类访问字段密码?

Now, is it possible to access field password from class User in ConstraintValidator implementaion class?

我是这样写的:

public class MatchValidator implements ConstraintValidator<Match, Object> {

private String mainField;
private String secondField;
private Class clazz;

@Override
public void initialize(final Match match) {
    clazz = User.class;

    final Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        if (field.isAnnotationPresent(Match.class)) {
            mainField = field.getName();
        }
    }

    secondField = match.field();
}

@Override
public boolean isValid(final Object value, final ConstraintValidatorContext constraintValidatorContext) {
    try {
        Object o; //Now how to get the User entity instance?

        final Object firstObj = BeanUtils.getProperty(o, mainField);
        final Object secondObj = BeanUtils.getProperty(o, secondField);

        return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
    } catch (final Exception ignore) {
        ignore.printStackTrace();
    }
    return true;
}
}

现在的问题是如何获取 User 对象实例并比较字段值?

Now the question is how can I get the User object instance and compare fields values?

推荐答案

你要么需要写一个 类级别约束,其中您将完整的 User 实例传递给 isValid 调用或你可以使用类似 @ScriptAssert.

You either need to write a class level constraint in which you get the full User instance passed into the isValid call or you can use something like @ScriptAssert.

目前无法访问根 bean 实例作为正常"字段验证的一部分.有一个 BVAL 问题 - BVAL-237 - 讨论添加此功能,但因此到目前为止,它还不是 Bean 验证规范的一部分.

At the moment it is not possible to access the root bean instance as part of a "normal" field validation. There is a BVAL issue - BVAL-237 - which discusses to add this functionality, but so far it is not yet part of the Bean Validation specification.

请注意,无法访问根 bean 是有充分理由的.对于 validateValue 情况,依赖于可访问的根 bean 的约束将失败.

Note, there are good reasons why the root bean is not accessible atm. Constraints which rely on the root bean being accessible will fail for the validateValue case.

这篇关于如何访问注释属性中描述的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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