对于T类型,该方法未定义

时间:2018-07-23 11:51:29

标签: java generics undefined undefined-function

我正在尝试此示例,但无法使其正常运行;它会抛出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));

或其他...

3 个答案:

答案 0 :(得分:1)

您可以解决此问题。正如您在评论中所述:

  

我有一些枚举都具有getFromInt方法

对方法稍加修改后,通过添加新参数(枚举的类型),可以使用reflection来调用所说的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);
    }
}

答案 1 :(得分:1)

由于您只是从int转换到新类型T,所以为什么不尝试传递lambda {{3 }}进行如下转换:

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;
    }
}

答案 2 :(得分: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;
}