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

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

问题描述

是否可以访问字段值,该字段值在注释中描述,该注释用于注释类中的另一个字段.

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;
}
}

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

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

推荐答案

您要么需要编写 @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.

请注意,有很多原因导致无法访问atm的根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天全站免登陆