Search code examples
javagenericsundefinedundefined-function

The method is undefined for the type T


I am trying this example, but can't make it work; it throws The method getFromInt(int) is undefined for the type T

T is a generic enum type

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

am calling the previous method as follows for example:

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

or

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

or etc...


Solution

  • You can hack your way around this. As you've stated in the comments:

    I have some enums which all have getFromInt method

    With a slight adaptation to the method, by adding a new parameter, the type of the enum, you can use reflection to invoke said getFromInt method:

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