Java:如何编写接受实现给定接口的枚举常量的泛型函数? [英] Java: How to write generic function that accepts Enum constants that implement a given interface?
问题描述
public interface MyInterface {}
然后我有几个扩展界面的枚举:
public enum A implements MyInterface {}
public enum B implements MyInterface {}
我想要一个只接受扩展这个接口的枚举的函数。我不能做:
public void MyFunction(MyInterface input)
因为在函数内部,我使用EnumSet.of(input)创建一个EnumSet。我可以做的是
public< T extends Enum< T>> void myFunction(T input)
因为在函数内部,我需要创建一个需要传递给另一个函数。那么有没有类型安全的方法来做这个w / o投射?
编辑:更正的界面定义。
public< T扩展Enum< T> &安培; MyInterface的> void myFunction(T input)
注意:您没有返回类型的方法。我在这里给了 void
。相应地改变。哦!并请遵循Java命名约定。方法名称应以小写字母开头。
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.
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.
这篇关于Java:如何编写接受实现给定接口的枚举常量的泛型函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!