views:

56

answers:

2

Hi,

I need to define a generic class, and the type parameter must be an enum. I think it should look something like

public class <T> MyClass<T extends Enum<T>> {

}

But I can't seem to figure out the exact syntax. I should mention that I need a way to refer to the type (within MyClass) that it is instantiated with.

Thanks!

+3  A: 
public class MyClass<T extends Enum<T>> { }
Dario
A: 

While the approved answer looks syntactically correct, what's the scenario for such a declaration? Are you trying to write some class that can operate on any enum-defined type, like java.util.EnumSet or java.util.EnumMap? It's an unusual arrangement, so be sure you really need it in order to meet your requirements.

seh
This is actually a use case you often have. For example, you could also create a TreeSet of type <T extends Comparable<T>>, meaning a set of things you can compare to each other.
Jorn
Yes, that's almost the Curiously Recurring Template Pattern, without the derivation. I was asking specifically about the use of Enum here. I took the question to be focused on Enum less than the generalized problem of writing such a generic declaration.
seh