Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 1000
mario_sunny Avatar asked Sep 06 '25 22:09

mario_sunny


1 Answers

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);
        }
    }
like image 52
zoomout Avatar answered Sep 08 '25 10:09

zoomout