我试图拥有一个扩展公共接口的枚举集合,因此类似于:
interface Fooable
{
void someCommonMethod();
}
enum E1 implements Fooable
{
// some enumuerations and a definition for someCommonMethod()
}
enum E2 implements Fooable
{
// some different enumerations and a different definition for someCommonMethod()
}然后在其他地方利用这一点,同时强制变量是Enum ,而实现了接口。所以一些类似于..。
bar(Enum<? extends Fooable> fe)
{
fe.ordinal();
fe.someCommonMethod();
}然而,到目前为止,我似乎不得不将fe转换为实现接口,即,
bar(Enum<? extends Fooable> fe)
{
fe.ordinal();
((Fooable)fe).someCommonMethod();
}虽然这应该是安全的。这似乎不太理想,而且我可能忽略了一些东西。当然,如果我试着把param作为一个傻瓜来传递,那么我最终会把它当作Enum来处理,这不仅是没有收益的,我现在甚至都不安全。见下文:
bar(Fooable fe)
{
// potentially unsafe cast!
((Enum<?>)fe).ordinal();
fe.someCommonMethod();
}有什么是我忽略的还是
Enum<? extends Fooable>就像我能得到的那样接近“好”解决方案?
我对Java还比较陌生,并且还在尝试像C或C++一样使用它,所以如果我把它当作一把锤子,而不是锯,或者忽略一些愚蠢的简单的东西,可以随意指出:)
发布于 2012-08-10 22:20:28
一个选项是将您需要的任何方法从Enum添加到Fooable,或者创建一个扩展Fooable并添加所需Enum方法的新接口。
示例:
interface Fooable {
void someCommonMethod();
}
interface FooableEnum extends Fooable {
int ordinal();
}
enum E1 implements FooableEnum {
// Implement someCommonMethod.
// ordinal() is already implemented by default.
}一旦您这样做了,您就可以在您的方法签名中使用FooableEnum作为参数类型,而不必担心任何泛型内容。
发布于 2012-08-10 21:55:44
这意味着T扩展Enum并实现Fooable:
<T extends Enum<T> & Fooable>因此,您的方法可以编写为:
<T extends Enum<T> & Fooable> void bar(T fe) {
fe.ordinal();
fe.someCommonMethod();
}https://stackoverflow.com/questions/11909579
复制相似问题