将接口的实现者强制为枚举 [英] Enforcing the implementer of an interface to be an enum
本文介绍了将接口的实现者强制为枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在一个集合中存储一个名为 App
的类型。 应用程序
需要是实现 App
界面的枚举。
组<应用>安装MyApps;
我已经定义了这样的界面...
界面App< T extends Enum< T>> {}
这几乎工作,例如,你不能这样做...
class MyClass实现Application&MyClass> {}
但是,你可以这样做...
枚举MyEnum实现应用程序< MyEnum> {}
class Myclass实现Application< MyEnum> {}
哪个错误。我只想要枚举能够实现这个界面,我该如何执行?
解决方案
定义一个方法,将元素添加到集合中,但使用该参数的约束...
public< E extends Enum&E; &安培; IMyInterface的> void addToSet(final E value){}
此后
addToSet(MyEnum.K)将编译
但是
addToSet(new Myclass())不会编译
pre>
I would like to store a type called
App
inside a set.App
needs to be an enum that implements theApp
interface.Set<App> myApps;
I have defined the interface like so...
interface App<T extends Enum<T>> {}
This is almost working, for example, you cannot do this...
class MyClass implements Application<MyClass> {}
However, you can do this...
enum MyEnum implements Application<MyEnum> {} class Myclass implements Application<MyEnum> {}
Which is wrong. I only want enums to be able to implement this interface, how can I enforce this?
解决方案Define a method that allows you to add Elements into the set, BUT use a constraint for that parameter...
public <E extends Enum<E> & IMyInterface> void addToSet(final E value) { }
now after that
addToSet(MyEnum.K) will compile
but
addToSet(new Myclass()) will NOT compile
这篇关于将接口的实现者强制为枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文