Restrict a generic type to an enumeration type to implement some interface

I have an enumeration that implements MyInterface. When creating another class using this enumeration, I want to restrict enumClz to the class that implemented MyInterface.

Therefore, I describe the signature as " T extends Enum< T extends MyInterface> " when declaring a generic type.

 public <T extends Enum< T extends MyInterface>> C1( Class<T> enumClz) { for (T anEnumConst : enumClz.getEnumConstants()) { //....process } } 

What surprised me was that the IDE says it is "unexpectedly associated" with " T extends MyInterface ". I do not know what this means with the help of such a message with two messages. Any decision on this?


And by the way, of the curious, I have a strange question, although not a very important one. Can the enumeration type T be equivalent to the next infinite loop

<T extends Enum< T extends Enum<T extends<....>>>> ?

+7
java generics enums
source share
1 answer

Declare instead the following:

 public <T extends Enum<T> & MyInterface> C1(Class<T> enumClz) 

Here we declare T have several upper bounds, which is possible for type parameters.

Declaring <T extends Enum<T extends MyInterface>> is not valid syntax because T must be type-limited, but T extends MyInterface in the type argument for Enum tries to add additional information about T when it has already been declared.

Note also that the class type must always be first when declaring multiple borders. The declaration <T extends MyInterface & Enum<T>> also invalid syntax.

And by the way, of the curious, I have a strange question, although not a very important one. Can enumeration type T be equivalent to the next infinite loop

<T extends Enum< T extends Enum<T extends<....>>>> ?

The T extends Enum<T> declaration is already "infinite" in that it is recursive. The same T that is declared is given as a type argument for its upper bound - the type parameter area includes its own declaration.

Additional Information:

+9
source share

All Articles