Java:特定枚举和通用 Enum<?>参数 [英] Java: specific enums and generic Enum<?> parameters
问题描述
我想将任何枚举值传递给实用程序类中的方法,并获得另一个相同枚举类型的枚举值.像这样:
I want to pass any enum value to method in utility class and get another enum value of same enum type. Something like this:
public class XMLUtils {
public static Enum<?> getEnumAttribute(Element element, String name,
Enum<?> defaultValue) {
if (element.hasAttribute(name)) {
String valueName = element.getAttribute(name);
// search for value
for (Enum<?> value: defaultValue.getClass().getEnumConstants())
if (value.toString().equalsIgnoreCase(valueName))
return value;
}
// not found, return default value
return defaultValue;
}
}
方法getEnumAttribute()
的使用:
// simple enum
public enum EUploadMethod {
INSERT, UPDATE, DELETE
}
// read enum value from XML config file
EUploadMethod method = XMLUtils.getEnumAttribute(element, "method",
EUploadMethod.INSERT);
此代码功能齐全,Eclipse 编译并运行它而不会出现警告或错误,而且它的工作原理非常棒.
This code is fully functional, Eclipse compiles and runs it without warnings or errors and it works like a charm.
但是,当我从命令行通过 Maven2 清理和编译项目时,它在 getEnumAttribute
调用的地方失败并出现错误:
But when I clean and compile project from command line by Maven2, it fails with error on line where is getEnumAttribute
called:
$ mvn clean compile
....
[ERROR] /home/.... DataUploader.java:[173,53] inconvertible types
found : java.lang.Enum<capture#414 of ?>
required: .....DataUploader.EUploadMethod
我在 Eclipse 和 Maven 中使用 Sun JDK 1.6:
I am using Sun JDK 1.6 in either Eclipse and Maven:
$ mvn -version
Apache Maven 2.2.1 (r801777; 2009-08-06 21:16:01+0200)
Java version: 1.6.0_14
Java home: /usr/lib/jvm/java-6-sun-1.6.0.14/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux" version: "2.6.27-17-generic" arch: "i386" Family: "unix"
问题:
为什么这段代码在 Eclipse 中是可编译和功能的,而编译在 Maven 中失败,据我所知使用相同的 javac 编译器?
Why this code is compilable and functional in Eclipse, and compile fails in Maven which using as far as I know same javac compiler?
将特定枚举传递给通用 Enum>
参数有什么问题?
What's wrong with passing specific enums to generic Enum<?>
parameters?
谢谢,
马丁·沙伊纳
推荐答案
Eclipse 编译器和 javac 有一些区别,尤其是在泛型方面.人们认为 eclipse 是正确的,但这没关系:)
Eclipse compiler and javac have some differences, especially when it comes to generics. It is believed that eclipse is correct, but that doesn't matter :)
试试
public static <T extends Enum<T>> Enum<T> getEnumAttribute(Element element, String name,
Enum<T> defaultValue) {
...
}
这篇关于Java:特定枚举和通用 Enum<?>参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!