Java:方法参数中的通用枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4325319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: generic enum in method parameter
提问by Ed Michel
Correspondig the following question:
对应以下问题:
Java: Enum parameter in method
I would like to know, how can I format the code to require enums generically.
我想知道,如何将代码格式化为一般需要枚举。
Foo.java
文件
public enum Foo {
a(1), b(2);
}
Bar.java
酒吧.java
public class Bar {
public Bar(generic enum);
}
Later on I'll have more enum classes like "foo", but you can still create bar containing any kind of enum class. I have "jdk1.6.0_20" by the way...
稍后我将有更多的枚举类,如“foo”,但您仍然可以创建包含任何类型的枚举类的 bar。顺便说一下,我有“jdk1.6.0_20”...
采纳答案by Sean Patrick Floyd
See the methods in EnumSetfor reference, e.g.
参见EnumSet 中的方法以供参考,例如
public static <E extends Enum<E>> EnumSet<E> of(E e)
(This method returns an EnumSet with one element from a given Enum element e)
(此方法返回一个 EnumSet,其中包含来自给定 Enum 元素 e 的一个元素)
So the generic bounds you need are: <E extends Enum<E>>
所以你需要的通用边界是: <E extends Enum<E>>
Actually, you will probably make Bar
itself generic:
实际上,您可能会使Bar
自己变得通用:
public class Bar<E extends Enum<E>> {
private final E item;
public E getItem(){
return item;
}
public Bar(final E item){
this.item = item;
}
}
You may also add a factory method like from
, with
etc.
您也可以添加像工厂方法from
,with
等等。
public static <E2 extends Enum<E2>> Bar<E2> with(E2 item){
return new Bar<E2>(item);
}
That way, in client code you only have to write the generic signature once:
这样,在客户端代码中,您只需编写一次通用签名:
// e.g. this simple version
Bar<MyEnum> bar = Bar.with(MyEnum.SOME_INSTANCE);
// instead of the more verbose version:
Bar<MyEnum> bar = new Bar<MyEnum>(MyEnum.SOME_INSTANCE);
Reference:
参考:
回答by gustafc
public class bar {
public <E extends Enum<E>> void bar(E enumObject);
}
The bar
method can now receive any kind of enum.
该bar
方法现在可以接收任何类型的枚举。
回答by André
You can also do it this way:
你也可以这样做:
public class Bar {
public Bar(Enum<?> e){}
}
Every enumeration extends Enum. Then you can use this if you need the enum constants:
每个枚举都扩展了 Enum。然后,如果您需要枚举常量,则可以使用它:
e.getDeclaringClass().getEnumConstants()