Auro
Auro

Reputation: 1638

How to make a custom annotation in Java that would allow parameters to have a value from a specified range?

I want to create an annotation that can be applied only to method parameters and should specify the range of values that parameters can accept.

Lets say I have an annotation @MyAnnotation and it accepts values from 0 to 255.

Now if I have the following method

public boolean isInRange(@MyAnnotation int value) {
.......
.......
}

and some class tries to call it the following way:

isInRange(300);

I want the annotation to give a warning saying the value is not acceptable and should be in the range (showing the range). I also don't want the compiler to compile it until correct value is passed to the method.

Now I know that @Target(ElementType.PARAMETER) causes the annotation to be applied only to parameters, but I don't know how to implement the range logic and also if the RetentionPolicy should be RetentionPolicy.SOURCE or RetentionPolicy.RUNTIME

Upvotes: 1

Views: 447

Answers (1)

mernst
mernst

Reputation: 8147

The @IntRange annotation of the Checker Framework. Does this. The Constant Value Checker enforces the property at compile time -- that is, the compiler warns you if a client of the method could pass an illegal value.

You could re-use that annotation, or study its implementation if you want your own annotation.

Upvotes: 1

Related Questions