1

我正在尝试这个例子,但不能让它工作;它抛出The method getFromInt(int) is undefined for the type T

T是一个通用枚举类型

public static <T> T deserializeEnumeration(InputStream inputStream) {
        int asInt = deserializeInt(inputStream);
        T deserializeObject = T.getFromInt(asInt);
        return deserializeObject;
    }

我正在调用前面的方法,例如:

objectToDeserialize.setUnit(InputStreamUtil.<Unit>deserializeEnumeration(inputStream));

或者

objectToDeserialize.setShuntCompensatorType(InputStreamUtil.<ShuntCompensatorType>deserializeEnumeration(inputStream));

或者等等……

4

3 回答 3

1

你可以解决这个问题。正如您在评论中所说:

我有一些枚举都有 getFromInt 方法

对该方法稍作修改,通过添加一个新参数,即枚举类型,您可以使用反射来调用所述getFromInt方法:

public static <T> T deserializeEnumeration(Class<? extends T> type, InputStream inputStream){
    try {
        int asInt = deserializeInt(inputStream);
        // int.class indicates the parameter
        Method method = type.getDeclaredMethod("getAsInt", int.class);
        // null means no instance as it is a static method
        return method.invoke(null, asInt);
    } catch(NoSuchMethodException, InvocationTargetException, IllegalAccessException e){
       throw new IllegalStateException(e);
    }
}
于 2018-07-23T12:10:55.967 回答
1

既然您只是从转换int为新类型T,为什么不尝试传入一个lambda 功能接口来进行转换,如下所示:

public class FunctionInterface {
    public static void main(String... args) {
        getT(1, String::valueOf);
    }

    private static <T> T getT(int i, Function<Integer, T> converter) {
        return converter.apply(i); // passing in the function;
    }
}
于 2018-07-23T12:36:52.433 回答
1
  1. 您尚未指定T具有方法getFromInt(int)
  2. 您正在尝试static从泛型参数调用方法 - 这将不起作用。

像这样的东西应该工作:

interface FromInt {
    FromInt getFromInt(int i);
}

enum MyEnum implements FromInt {
    Hello,
    Bye;

    @Override
    public FromInt getFromInt(int i) {
        return MyEnum.values()[i];
    }
}

public static <T extends Enum<T> & FromInt> T deserializeEnumeration(Class<T> clazz, InputStream inputStream) {
    int asInt = 1;
    // Use the first element of the `enum` to do the lookup.
    FromInt fromInt = clazz.getEnumConstants()[0].getFromInt(asInt);
    return (T)fromInt;
}
于 2018-07-23T12:38:14.680 回答