Java: How to write generic function that accepts Enum constants that implement a given interface?

一曲冷凌霜 提交于 2019-12-07 07:27:28

问题


So i have a bunch of enum's that all extend an interface:

public interface MyInterface {}

I then have several enums that extend the interface:

public enum A implements MyInterface {}

public enum B implements MyInterface {}

I want a function that will accept only enum's that extend this interface. I cannot do:

public void MyFunction(MyInterface input)

because, inside the function, I create an EnumSet using EnumSet.of(input). I cannod do

public <T extends Enum<T>> void myFunction(T input)

because, inside the function, I need to create a Map that needs to be passed to another function. So is there any type-safe way to do this w/o casting?

Edit: Corrected interface definitions.


回答1:


You can give multiple bounds to your type parameter:

public <T extends Enum<T> & MyInterface> void myFunction(T input)

Note: You're missing return type of the method. I've given void here. Change accordingly. Oh! And please follow Java naming conventions. Method name should start with lowercase letters.



来源:https://stackoverflow.com/questions/21707681/java-how-to-write-generic-function-that-accepts-enum-constants-that-implement-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!