[ACCEPTED]-How can I require a generic parameter to be an enum that implements an interface?-enums

Accepted answer
Score: 102

Use an '&' instead:

public class MyWidget<T extends Enum<T> & MyInterface> {
    ...
}

The JLS calls this an "intersection 7 type", but I can find no mention of 6 it in the Java tutorials. I'll just say 5 that it does exactly what you were wishing 4 that "extends" would do.

Also, I should 3 mention that you can have as many types 2 as you want in the intersection type. So 1 if you wanted, you could do:

public class MyWidget<T extends Enum<T> & MyInterface & Serializable & Cloneable> {
    ...
}

[Note: this code sample should not be construed as an endorsement of the Cloneable interface; it was merely handy at the time.]

Score: 1

The JSR 203 (new new IO) stuff for JDK 7 7 is making a lot of use of enums that implement 6 interfaces (for example: http://openjdk.java.net/projects/nio/javadoc/java/nio/file/FileVisitOption.html) to allow them 5 some wiggle room in the future for future 4 additional sets of enum options. So that 3 is a feasible approach and obviously one 2 that was chosen after a lot of thought in 1 one large Sun project.

More Related questions