1

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!

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
Dónal
  • 185,044
  • 174
  • 569
  • 824

2 Answers2

3
public class MyClass<T extends Enum<T>> { }
Dario
  • 48,658
  • 8
  • 97
  • 130
0

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
  • 14,999
  • 2
  • 48
  • 58
  • This is actually a use case you often have. For example, you could also create a TreeSet of type >, meaning a set of things you can compare to each other. – Jorn Nov 20 '09 at 23:27
  • 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 Nov 20 '09 at 23:46