I have enum that implement MyInterface. While making other class using that enum I want to constrain the enumClz to be class that has implemented MyInterface.
So I describe signature to be "T extends Enum< T extends MyInterface>
" at generic type declaration.
public <T extends Enum< T extends MyInterface>> C1( Class<T> enumClz) {
for (T anEnumConst : enumClz.getEnumConstants()) {
//....process
}
}
What surprised me is the IDE say it is "unexpected bound" at "T extends MyInterface
".
I don't know what it means by such two word error message, Any solution about this?
And by the way, out of curious I have an odd question though not really important. Can an enum type T be equivalent to the following infinite loop
<T extends Enum< T extends Enum<T extends<....>>>>
?
Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.
On a technical level, there's nothing wrong with using an enum as the type used in a generic type.
C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.
A type constraint on a generic type parameter indicates a requirement that a type must fulfill in order to be accepted as a type argument for that type parameter. (For example, it might have to be a given class type or a subtype of that class type, or it might have to implement a given interface.)
Declare the following instead:
public <T extends Enum<T> & MyInterface> C1(Class<T> enumClz)
Here, we're declaring T
to have multiple upper bounds, which is possible for type parameters.
The declaration <T extends Enum<T extends MyInterface>>
is invalid syntax because T
must be bounded with a concrete type, but the T extends MyInterface
in the type argument for Enum
is trying to add more information about T
when it's already been declared.
Note also that a class type must always come first when declaring multiple bounds. A declaration of <T extends MyInterface & Enum<T>>
is also invalid syntax.
And by the way, out of curious I have an odd question though not really important. Can an enum type
T
be equivalent to the following infinite loop
<T extends Enum< T extends Enum<T extends<....>>>>
?
The declaration T extends Enum<T>
is already "infinite" in that it's recursive. The same T
that is being declared is given as a type argument for its upper bound - a type parameter's scope includes its own declaration.
More information:
Enum<E extends Enum<E>>
"?If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With