Parameter validators
This page explains how to create ParameterValidators that perform checks against parameters after they are supplied by the user.
Implementing a Custom ParameterValidator
ParameterValidatorStep 1: Define the @Range Annotation
@Range Annotationimport java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Range {
double min();
double max();
}@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class Range(val min: Double, val max: Double)Step 2: Implement the RangeValidator
RangeValidatorpublic enum RangeValidator implements ParameterValidator<CommandActor, Number> {
INSTANCE;
@Override
public void validate(@NotNull CommandActor actor, Number value, @NotNull ParameterNode<CommandActor, Number> parameter, @NotNull Lamp<CommandActor> lamp) {
Range range = parameter.getAnnotation(Range.class);
if (range == null) return;
double d = value.doubleValue();
if (d < range.min())
throw new CommandErrorException("Specified value (" + d + ") is less than minimum " + range.min());
if (d > range.max())
throw new CommandErrorException("Specified value (" + d + ") is greater than maximum " + range.max());
}
}object RangeValidator : ParameterValidator<CommandActor, Number> {
override fun validate(
actor: CommandActor,
value: Number,
parameter: ParameterNode<CommandActor, Number>,
lamp: Lamp<CommandActor>
) {
val range = parameter.getAnnotation(Range::class.java) ?: return
val d = value.toDouble()
if (d < range.min)
throw CommandErrorException("Specified value ($d) is less than minimum ${range.min}")
if (d > range.max)
throw CommandErrorException("Specified value ($d) is greater than maximum ${range.max}")
}
}Step 3: Register the Validator
Step 4: Using the @Range Annotation in Commands
@Range Annotation in CommandsLast updated
Was this helpful?