Java:特定枚举和泛型枚举<?>参数 [英] Java: specific enums and generic Enum<?> parameters

查看:1186
本文介绍了Java:特定枚举和泛型枚举<?>参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将任何枚举值传递给实用程序类中的方法,并获取相同枚举类型的另一个枚举值。这样的东西:

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编译并运行它时不会出现警告

但是当我从命令行通过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

我使用Sun JDK 1.6 Eclipse和Maven:

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"

问题:


  1. 为什么这个代码是可编译的和在Eclipse中的功能,并且编译在Maven中失败,尽管我知道相同的javac编译器?

  1. 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?

感谢,

Martin Schayna

Martin Schayna

推荐答案


  1. Eclipse编译器和javac有一些区别,尤其是当涉及泛型时。相信日食是正确的,但这并不重要)。

  1. 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) {
   ...
}

/ li>

这篇关于Java:特定枚举和泛型枚举&lt;?&gt;参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆