java 字段 属性_java-如何访问注释属性中描述的字段

是否可以访问字段值,其中在注释中描述了字段名称,该注释对类中的另一个字段进行了注释.

例如:

@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类访问字段密码?

编辑:

我写了这样的东西:

public class MatchValidator implements ConstraintValidator {

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;

}

}

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值