Defining Java variables that take only a specific range of values

Is there a built-in way to define fields / variables that take values ​​in a specific range? I mean a way to resolve it at compile time .

For example, the definition of a double variable that takes values ​​only between 1-10.

+4
source share
5 answers

No, because at compile time it is not possible to find out if your software logic will output values ​​out of range. And at run time, there is no implementation for it supported by the native sdk. However, you can wrap type classes (for example, Create class MyInteger with an Integer instance as a member wrapped with range checking methods in the MyInteger class)

+3
source

Closest you can get

1) create an Enum for your range of values, for which enumerations are intended.

 public Enum MyVals { ONE(1) TWO(2) ... private int val; MyVals(int val) { this.val = val; } } 

see this . Of course, this will only work if the values ​​are discrete (i.e. don't float)

2) make the field private and write a smart setter that explodes with an invalid value.

 public void setVal(int val) { if (val < 0 || val > 10) throw....; this.val = val; } 
+5
source

While the compile-time parameter is not used to indicate the range, another approach is to use a validation framework such as the Hibernate Validator . You annotate your field using annotation like @Range (min =, max =) . To validate an object, you use the validator object validation method .

+1
source

The closest thing to what you're talking about is an enumeration that allows you to specify a set of patch values. It is not possible to declare an integer, but limit the valid values ​​that it may have. You could create your own type and provide such a restriction.

0
source

you can use enumerations for such a set. but I think that you also need some meaningful comparison of values. in this case, support a HashTable search, with the key as an enumeration and the value you want.

0
source

All Articles