Unchecked cast from X to generic type that extends X

923 Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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

try replacing the line that produces unchecked cast warning with

T convertedObject = anyClassYouWant.cast(result);