The following code compiles (and runs the tests as expected) in Eclipse:
import java.util.EnumSet; public class EnumTest { static enum Cloneables implements Cloneable { One, Two, Three; } public <T extends Cloneable> T getOne(Class enumType) { EnumSet<? extends T> set = EnumSet.allOf(enumType); return set.iterator().next(); } }
However, compiling with javac (JDK 7) directly or through Maven fails with the following error:
type argument ? extends T is not within bounds of type-variable E
Honestly, the complexity of enums + interfaces + type-parameters (generics) during the game immediately threw me away when I wrote the code, but I thought I finally understood.
The goal is to write the calling code as follows:
Cloneable something = enumTest.getOne(Cloneables.class);
For example, in Eclipse, the following test compiles and passes:
@Test public void testGetFirst() { assertSame(Cloneables.One, getOne(Cloneables.class)); }
Any tips that are "correct", "Eclipse" or "javac" are appreciated.
Any advice on alternative ways of implementing the idea is also appreciated: take a class as a parameter to a method that can be used in EnumSet.allOf() , and which also determines the type of Enum objects in EnumSet
By the way, do not criticize the purpose of this method; I reduced it from more useful / meaningful code. I am not interested in discussing the merits of "finding the first element from an enum type" - this is not a question of this question.