I have several enums that can be found by an int. This is done by a static method on the enum. For example:
enum Foo {
A, B, C, D, ... ;
public static Foo fromInt(int i) {
switch(i) {
case 15: return A;
case 42: return B;
...
}
}
enum Bar {
BLA, BOO, BEE, ... ;
public static Bar fromInt(int i) {
switch(i) {
case 78: return BLA;
case 22: return BOO;
...
}
}
...
Now in some code I have a generic type T
that is guaranteed to be one of these enums and I have an integer i
. How can I call the fromInt
method and get the instance of the enum by value i
?
I have tried creating an interface with a static method fromInt
and let the enums implement it, but static methods do not work in interfaces.
I can not use Java 8.
But when there is a need to achieve multiple inheritance enum can implement any interface and in java, it is possible that an enum can implement an interface. Therefore, in order to achieve extensibility, the following steps are followed:
enum can contain a constructor and it is executed separately for each enum constant at the time of enum class loading. We can’t create enum objects explicitly and hence we can’t invoke enum constructor directly. enum can contain both concrete methods and abstract methods.
Getting Enum Constants by Name To get an enum constant by its String name, we use the valueOf () static function: 5.2. Iterating Through Enum Constants To iterate through all enum constants, we use the values () static function: 5.3. Static Methods To add a “static” function to an enum, we can use a companion object:
valueOf () method returns the enum constant of the specified string value, if exists. enum can contain a constructor and it is executed separately for each enum constant at the time of enum class loading. We can’t create enum objects explicitly and hence we can’t invoke enum constructor directly.
Short answer you can't
Long answer you can either pass Class
of that enum to your method and invoke fromInt
by reflection or create factory interface and implent it for each your enum then pass right instance to your method.
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