I have an instanceof an Java annotation which has a target of METHOD: is it possible to get the Method object that it's attached to?
I'm trying to do cross-parameter validation, where the validator will apply logic to the combination of parameters to determine if they are correct. However, since the validator can be applied to multiple methods, I'm looking for a way to flag which parameters are which.
For example, in the example below, I have methods that use two arguments to specify a range by a start and an end. I want a Validator to check that the start is not greater than the end. I want to use annotations on the parameters to indicate which parameter is the start and which is the end, and then have the validator use those annotations to determine which parameters to use in the validation.
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface StartParam {}
/***************************/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface EndParam {}
/***************************/
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = RangeParamsValidator.class)
@SupportedValidationTarget(ValidationTarget.PARAMETERS)
public @interface RangeParams { }
/***************************/
public class RangeParamsValidator implements ConstraintValidator<RangeParams, Object[]> {
private int indexOfStartArg;
private int indexOfEndArg;
@Override
public void initialize(
RangeParams constraintAnnotation
) {
// This is where I'm hoping to get the method that `constraintAnnotation`
// is attached to, so I can iterate over its params and see which are
// annotated with @StartParam and @EndParam so I can set indexOfStartArg
// and indexOfEndArg;
}
@Override
public boolean isValid(Object[] value, ConstraintValidatorContext context) {
Integer start = value[indexOfStartArg];
Integer end = value[indexOfEndArg];
return start <= end;
}
}
/***************************/
// Example use:
class Whatever {
@RangeParams
void doSomething(
String ignoreThisArg,
@StartParam int start,
@FinishParam int finish,
Object ignoreThisToo
) {
// ...
}
}