I'm using the term "constant" loosely. I'm referring specifically to public static int
's, which the compiler is free to treat as immediates.
I have legacy code that ensures that a value is established as 3 or greater in the following inelegant way:
public SomeClass
{
public static final int BORDER;
static
{
BORDER = 3;
if (BORDER < 3) throw new UnsupportedOperationException(
String.format("This program was compiled with a BORDER of [%d], "+
"and a value of 3 or greater MUST be used.", BORDER));
}
}
I'm looking for a standard annotation that can enforce this at compile-time.
I imagine something akin to
@Min(3)
public static final int BORDER=2; //compile-time error
or
@Enforce("BORDER >= 3")
public static final int BORDER=2; // compile-time error
Does some facility approximating this exist?
The Constant Value Checker of the Checker Framework has an @IntRange
annotation that does what you want.
If you annotate the type of a variable like this:
@IntRange(from=0, to=11) int month;
then at compile time, the compiler will issue an error anywhere in the program that month
might take on a value outside of the range 0..11. You can write just one of the bounds; in your case, you would use
public static final @IntRange(from=3) int BORDER=2; // compile-time error