4

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.

mario_sunny
  • 1,412
  • 11
  • 29
  • 1
    Can you change the method so that it accepts a `Class`? It will then be easy to actually do the checking. As it stands, the warning is right on the money - you have no way of knowing that the method returns the correct object type. – RealSkeptic Feb 11 '19 at 16:49
  • @RealSkeptic Yes that is a possibility, and that would fix my issue. I will hold out for other solutions though, as your solution would involve some tricky refactoring. – mario_sunny Feb 11 '19 at 16:53
  • Are you sure that `(T) result` is a conform cast in your case? – dehasi Feb 11 '19 at 16:53
  • @dehasi I don't know what you mean by _conform cast_. – mario_sunny Feb 11 '19 at 16:54

2 Answers2

3

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);
        }
    }
zoomout
  • 399
  • 3
  • 6
  • 1
    Or for greater generality: `public T someMethod(Class type)` if the caller knows that the result is a subtype of `T` and prefers to pass that subtype. It only removes the warning, of course: A `ClassCastException` will happen if `someExternalMethod` doesn’t return the expected type. – Ole V.V. Feb 11 '19 at 17:03
0

try replacing the line that produces unchecked cast warning with

T convertedObject = anyClassYouWant.cast(result);
ferpel
  • 206
  • 3
  • 12