I have the following code
public interface SomeInterface { }
public class TestConstants {
public static <E extends Enum<E> & SomeInterface> E getEnumString(Class<E> clazz, String s){
for(E en : EnumSet.allOf(clazz)){
if(en.name().equalsIgnoreCase(s)){
return en;
}
}
return null;
}
public enum A implements SomeInterface {
V1,
V2,
V3;
}
public enum B implements SomeInterface {
V1,
V2,
V3;
}
// And so on.......
}
Elsewhere in the code I can call call
TestConstants.getEnumString(TestConstants.B.Class,"V2")
and it will return TestConstants.B.V2
All is good.
But my question is what if I don't know the actual Enum class I will search i.e.
Class<?> enumClass
contains one of the Enums, but I don't know which.
Now I from code that is external to the TestConstants class, I could use something like the following
if (enumClass.equals(TestConstants.A.class)) {
TestConstants.getEnumString(TestConstants.A.class,value);
} else if (enumClass.equals(TestConstants.B.class)) {
TestConstants.getEnumString(TestConstants.B.class,value);
} else if (enumClass.equals(TestConstants.C.class)) {
// And so on....
But I'd really like to move this code into the TestConstants class. but I don't seem to be able to. If I add this function for example
public static <E extends Enum<E> & SomeInterface> E fromUnknownClass(Class<?> enumClass, String name) {
if (enumClass.equals(TestConstants.A.class)) {
return TestConstants.fromString(TestConstants.A.class,name); <-- Compile error
} else if .......
.......
}
I get the following compile error
incompatible types: inference variable E has incompatible bounds equality constraints:
TestConstants.A upper bounds: E,java.lang.Enum<E>,SomeInterface
Is what I'm trying for here even possible, or is there some Generics magic that I'm not aware of?