代码之家  ›  专栏  ›  技术社区  ›  Salem Masoud

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

  •  0
  • Salem Masoud  · 技术社区  · 6 年前

    我正在尝试这个例子,但不能使它工作;它抛出 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 回复  |  直到 6 年前
        1
  •  1
  •   Lino    6 年前

    你可以绕过这个。正如你在评论中所说:

    我有一些枚举,它们都有getFromInt方法

    只要稍微适应该方法,通过添加一个新参数(枚举的类型),就可以使用 reflection 调用said 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);
        }
    }
    
        2
  •  1
  •   Hearen    6 年前

    既然你只是 转换 int 到新类型 T 你为什么不试着通过 lambda 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;
        }
    }
    
        3
  •  1
  •   OldCurmudgeon    6 年前
    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;
    }