[英]Why do I get this error “Type mismatch: cannot convert from Serializable to T”?
With the the following code: 使用以下代码:
Main.java Main.java
// ...
private static <T extends Serializable> T doStuff() {
Response r = ...
// ...
return r.getDetails();//Error here
}
// ...
Response.java Response.java
interface Response {
// ...
Serializable getDetails();
// ...
}
I get this compile error : "Type mismatch: cannot convert from Serializable to T" in the doStuff
method. 我收到此编译错误:
doStuff
方法中出现“类型不匹配:无法从序列化转换为T”。
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
. 但是现在我有了这个警告:
Type safety: Unchecked cast from Serializable to T
@SuppressWarnings("unchecked")
would suppress the warning but I find this solution ugly. @SuppressWarnings("unchecked")
将禁止显示警告,但是我发现此解决方案很难看。
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
. 问题是,根据您的代码,每个
T
必须是一个可Serializable
,但并非每个Serializable
也是一个T
Assuming that both T1
and T2
were Serializable
, the following would also cause problems: 假设
T1
和T2
都是可Serializable
,则以下内容也会引起问题:
T1 t = new T2();
as T1
and T2
are not related, even though they are both Serializable
. 因为
T1
和T2
不相关,即使它们都是Serializable
。
You have to cast your returned Object to T
type 您必须将返回的对象转换为
T
类型
like this: 像这样:
return (T) r.getDetails();
UPDATE 更新
Then you have to make your Response
interface or getDetails()
method generic. 然后,您必须使
Response
接口或getDetails()
方法通用。
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: 如果您提供的实施细节太少,我建议使
Response
通用:
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.
问题是Thorsten Dittmar已经写了什么。
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;
}
}));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.