Variable field in a constraint annotation
Posted
by Javi
on Stack Overflow
See other posts from Stack Overflow
or by Javi
Published on 2010-03-18T11:40:54Z
Indexed on
2010/03/18
11:51 UTC
Read the original article
Hit count: 394
Hello,
I need to create a custom constraint annotation which can access the value of another field of my bean. I'll use this annotation to validate the field because it depends on the value of the other but the way I define it the compiler says "The value for annotation attribute" of my field "must be a constant expression".
I've defined it in this way:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=EqualsFieldValidator.class)
@Documented
public @interface EqualsField {
public String field();
String message() default "{com.myCom.annotations.EqualsField.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class EqualsFieldValidator implements ConstraintValidator<EqualsField, String>{
private EqualsField equalsField;
@Override
public void initialize(EqualsField equalsField) {
this.equalsField = equalsField;
}
@Override
public boolean isValid(String thisField, ConstraintValidatorContext arg1) {
//my validation
}
}
and in my bean I want something like this:
public class MyBean{
private String field1;
@EqualsField(field=field1)
private String field2;
}
Is there any way to define the annotation so the field value can be a variable?
Thanks
© Stack Overflow or respective owner