简体   繁体   中英

Java Annotation to enforce a compile-time minimum value of a constant?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM