简体   繁体   中英

Why do I get this error “Type mismatch: cannot convert from Serializable to T”?

With the the following code:

Main.java

 // ...

 private static <T extends Serializable> T doStuff() {
     Response r = ...

     // ...

     return r.getDetails();//Error here
 }

 // ...

Response.java

 interface Response {
    // ...

    Serializable getDetails();

    // ...
 }

I get this compile error : "Type mismatch: cannot convert from Serializable to T" in the doStuff method.

If I cast the returned result , the error is removed.

  return (T)r.getDetails();

But now I have this warning : Type safety: Unchecked cast from Serializable to T . @SuppressWarnings("unchecked") would suppress the warning but I find this solution ugly.

Is there any better option ?

The problem is that by your code, every T must be a Serializable , but not every Serializable is also a T .

Assuming that both T1 and T2 were Serializable , the following would also cause problems:

T1 t = new T2();

as T1 and T2 are not related, even though they are both Serializable .

You have to cast your returned Object to T type
like this:

return (T) r.getDetails();

UPDATE

Then you have to make your Response interface or getDetails() method generic.
like this:

interface Response<T extends Serializable> {
// ...

T getDetails();

}

or

interface Response {
// ...

<T extends Serializable> T getDetails();

}

Provided that you give too little implementation details I would suggest to make Response generic:

private static <T extends Serializable> T doStuff() {
    Response<T> r = ...;

// ...

    return r.getDetails();
}

interface Response<T extends Serializable> {
    // ...

    T getDetails();

    // ...
}

But that won't necessary work with the rest of the thing you might have. The problem is what Thorsten Dittmar already wrote.

All of following compiles w/o warnings and should give you an idea:

interface Response<T extends Serializable> {
    T getResponse();
}


class Sample {
    private static <T extends Serializable> T get(Response<T> generator) {
        return generator.getResponse();
    }

    public static void main(String[] args) {
        System.out.println(get(new Response<Serializable>() {
            @Override
            public String getResponse() {
                return "string";
            }
        }));
        System.out.println(get(new Response<Serializable>() {
            @Override
            public Integer getResponse() {
                return 1;
            }
        }));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM