简体   繁体   English

Enum的Java通用绑定(约束)

[英]Java Generic bound (constraint) for Enum

I'm trying to bound (constrain) a Java generic type variable to be an enum (any enum) and failing. 我试图绑定(约束)Java泛型类型变量为枚举(任何枚举)并失败。 Might you be able to tell me why? 你能告诉我为什么吗?

import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.cellprocessor.ift.StringCellProcessor;

public class ParseEnum<TEnum extends Enum> extends CellProcessorAdaptor implements StringCellProcessor {

    public Object execute(final Object value, final CsvContext context) {
        ...
        final TEnum result;
        if (value instanceof TEnum) {
            result = (TEnum) value;
        } else if( value instanceof String ) {
                result = TEnum.valueOf((String)value);
        } else {
            ...
        }
        ...
}

(These are bits of my actual code attempting to extend a SuperCSV CellProcessor. ) (这些是我试图扩展SuperCSV CellProcessor的实际代码的一部分。)

value instanceof TEnum gives me this error (in Eclipse): value instanceof TEnum给了我这个错误(在Eclipse中):

"Cannot perform instanceof check against type parameter TEnum. Use its erasure Enum instead since further generic type information will be erased at runtime" “无法对类型参数TEnum执行instanceof检查。请使用其擦除枚举,因为在运行时将删除其他泛型类型信息”

TEnum.valueOf((String)value) gives me this error: TEnum.valueOf((String)value)给出了这个错误:

"The method valueOf(Class, String) in the type Enum is not applicable for the arguments (String)" “Enum类型中的方法valueOf(Class,String)不适用于参数(String)”

You'll have to pass the enum class to do that (just like EnumSet.allOf() does). 你必须传递枚举类才能做到这一点(就像EnumSet.allOf()一样)。

public class ParseEnum<TEnum extends Enum<TEnum>> extends CellProcessorAdaptor implements StringCellProcessor {

    private Class<TEnum> enumType;

    public ParseEnum(Class<TEnum> enumType) {
        this.enumType = enumType;
    }

    public Object execute(final Object value, final CsvContext context) {
        ...
        final TEnum result;
        if (value.getClass().equals(enumType)) {
            result = (TEnum) value;
        } 
        else if (value instanceof String) {
            result = Enum.valueOf(enumType, (String) value);
        } 
        else {
            ...
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM