Mismatch between the Eclipse compiler and javac - enumerations, interfaces, and generics

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.

+5
source share
1 answer

You need to make sure that T is an enum type or that it will not comply with the restrictions for EnumSet :

 public <T extends Enum<T> & Cloneable> T getOne(Class enumType) 

In addition, you do not need a template in EnumSet , and you should not use the raw Class type:

 public <T extends Enum<T> & Cloneable> T getOne(Class<T> enumType) { EnumSet<T> set = EnumSet.allOf(enumType); return set.iterator().next(); } 
+4
source

Source: https://habr.com/ru/post/1210197/


All Articles