How can I require a generic parameter to be an enum that implements an interface?

后端 未结 2 1617
臣服心动
臣服心动 2020-12-12 19:21

I\'m not 100% convinced that this is a good idea, but I bumped into some code today that\'s currently implemented as:

class MyWidget 

        
相关标签:
2条回答
  • 2020-12-12 19:37

    Use an '&' instead:

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

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

    Also, I should mention that you can have as many types as you want in the intersection type. So 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.]

    0 讨论(0)
  • 2020-12-12 19:37

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

    0 讨论(0)
提交回复
热议问题