Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static methods in interfaces not working, how to get specific enum value out of several enums?

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.

like image 941
Mark Buikema Avatar asked Aug 29 '16 14:08

Mark Buikema


People also ask

Can enum implement any interface in Java?

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:

Can an enum have a constructor?

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.

How do you get the constant of an enum?

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:

What is the use of enum valueOf () method?

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.


1 Answers

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.

like image 109
talex Avatar answered Oct 24 '22 02:10

talex