Bartis Áron Bartis Áron - 3 months ago 8
Java Question

Static field with generic parameter extending multiple types

What I have without any problem:

I have multiple enums which extend the same interface:

interface CommonMethods
{

}

enum E1 implements CommonMethods
{
O1, O2
}

enum E2 implements CommonMethods
{
O3, O4
}


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 thos 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.

So the question:

What can I do to keep the constraint?

Disclaimer: This is just a dummy and not the real code with which I'm currently tryig to work. Please focus on my question! Thank you!

Answer

Declare the type as:

static <L extends Enum<CommonMethods>> void m(L l) {}

I have struck this issue myself before and after a lot of research, I have concluded that this is identical in effect to the type intersection.

Comments