javajava-8castingunchecked-castunchecked-conversion

Unchecked cast from X to generic type that extends X


I've been tasked with removing as many @SupressWarnings as possible in our codebase, and I'm not sure how to get around this particular issue.

I have this external method that returns a Serializable object, and a generic type T extends Serializable that I would like to cast the object to.

Here is a simplified version of the code:

class A <T extends Serializable> {

    public T someMethod() {
        Serializable result = someExternalMethod(...);
        T convertedObject = (T) result; // produces unchecked cast warning

        return convertedObject;
    }
}

Is it possible to perform this conversion without producing an unchecked cast warning (assuming the external method cannot be changed)?

This is Java 8.


Solution

  • To extend the answer of ferpel you can pass the type as a parameter

        class A <T extends Serializable> {
    
            public T someMethod(Class<T> type) {
                Serializable result = someExternalMethod(...);
                return type.cast(result);
            }
        }