该方法对于类型 T 是未定义的

The method is undefined for the type T

我正在尝试这个例子,但无法让它工作;它抛出 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));

或等等...

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

I have some enums which all have getFromInt method

稍微调整一下方法,通过添加一个新参数,即枚举的类型,您可以使用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);
    }
}

既然你只是int转换为新类型T,你为什么不尝试传入一个[=13] =] functional interface 做如下转换:

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