I have this enum:
public enum Digits {
ZERO(0);
private final int number;
private Digits(int number) {
this.number = number;
}
public int getValue(){
return number;
}
}
And I would like to make setter in another class which can me offer following feature: - I will give it integer value (in this case, 0) and that setter will set enum ZERO to my local variable of type Digits Is that possible? Many thanks!
It is possible, but not by invoking the enum
's constructor, as it's available only within the enum itself.
What you can do is add a static
method in your enum
that retrieves the correct instance based on a given value, e.g. ZERO
if the given value is 0
.
Then you'd invoke that method in your other class when given the int
argument.
Self contained example
public class Main {
static enum Numbers {
// various instances associated with integers or not
ZERO(0),ONE(1),FORTY_TWO(42), DEFAULT;
// int value
private int value;
// empty constructor for default value
Numbers() {}
// constructor with value
Numbers(int value) {
this.value = value;
}
// getter for value
public int getValue() {
return value;
}
// utility method to retrieve instance by int value
public static Numbers forValue(int value) {
// iterating values
for (Numbers n: values()) {
// matches argument
if (n.getValue() == value) return n;
}
// no match, returning DEFAULT
return DEFAULT;
}
}
public static void main(String[] args) throws Exception {
System.out.println(Numbers.forValue(42));
System.out.println(Numbers.forValue(10));
}
}
Output
FORTY_TWO
DEFAULT
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With