You need to have a class level annotation for this. Field level annotations only access value of the fields.
Here is an example:
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
// Custom annotation
@Target({ TYPE })
@Retention(RUNTIME)
@Repeatable(NotGreaterThans.class)
@Documented
@Constraint(validatedBy = { NotGreaterThanValidator.class }) // Explicitly define validator
public @interface NotGreaterThan {
String source();
String target();
double percentage()
String message() default "Default message ..";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({ TYPE })
@Retention(RUNTIME)
@Documented
@interface NotGreaterThans {
NotGreaterThan[] value();
}
}
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
// Validator accesses both annotation and object value
public class NotGreaterThanValidator implements ConstraintValidator<NotGreaterThan, Object> {
private String source;
private String target;
private double percentage;
@Override
public void initialize(NotGreaterThan notGreaterThan) {
this.source = notGreaterThan.source();
this.target = notGreaterThan.target();
this.percentage = notGreaterThan.percentage();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
BigDecimal sourceValue = customMethodToGetFieldValue(source, value);
BigDecimal targetValue = customMethodToGetFieldValue(target, value);
return source.compareTo(target.multiply(percentage)) <= 0;
}
private BigDecimal customMethodToGetFieldValue(String fieldName, Object object) {
return ....
}
}
// Define your annotation on type
@NotGreaterThan(source ="a", target="b", percentage =50.0)
public class MyCustomBodyClass {
private BigDecimal a;
private BigDecimal b;
}
I haven't tested this, but should give you a head start.