What I have without any problem:
I have multiple enums which extend the same interface:
interface CommonMethods {
// some methods
}
enum E1 implements CommonMethods {
O1, O2;
// interface method impls
}
enum E2 implements CommonMethods {
O3, O4;
// interface method impls
}
I wanted to handle these by their common successors: Enum
and CommonMethods
.
So far I have methods like this:
static <L extends Enum<?> & CommonMethods> void m(L l) {}
So I can do with those enums what I want for example by calling methods from the CommonMethods interface.
Now the problem begins:
But I also want to store some of these in a static list field of a class like this:
class Test1 {
static List<Enum<?> & CommonMethods> l = new LinkedList<>();
static {
l.add(E1.O1);
l.add(E2.O3);
}
}
This gives me compiler error. I have a workaround solution which to my opinion is bad:
class Test2 {
static List<Enum<?>> l = new LinkedList<>();
static {
l.add(E1.O1);
l.add(E2.O3);
}
static <L extends Enum<?> & CommonMethods> void m(L l) {}
}
This way I lose the constraint of the acceptable types.
What can I do to keep the constraint?
Note: This is just a dummy and not the real code with which I'm currently trying to work, so please refrain from refactoring suggestions.