Skip to content
Advertisement

Java enum with generic attributes

I have been trying to create enum that contains generic attribute, for example:

public enum SomeEnum {
    SOME_VALUE_1(SomeValue1.class),
    SOME_VALUE_2(SomeValue2.class);

    private final Class<T extends SomeValue> className;
}

SomeValue1 and SomeValue2 classes implement SomeValue interface. For some reason <T extends SomeValue> is marked with “Unexpected bound” error. If I replace T with ?, there is no error. But it is still puzzling me why it is happening when I use T.

Any help would be highly appreciated.

Advertisement

Answer

When you use T extends SomeValue in this way, you are referencing a type variable T that isn’t defined, and you aren’t allowed to define a type variable there. Only on type variable declarations are you allowed to define a bound such as T extends SomeValue.

On an interface or class, you could define T with the bound you want, but not on an enum. Enums are not allowed to be generic in Java.

You are probably getting the same error on the constructor you haven’t shown that accepts a Class<T extends SomeValue> to assign to className. The same reason applies here too.

Using ? extends SomeValue is an upper-bounded wildcard. It basically means “a specific yet unknown type that is SomeValue or a subtype”. This is appropriate here, because all you care about here is that the Class is for SomeValue or some implementation class.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement