【发布时间】:2018-08-17 20:26:51
【问题描述】:
我有以下代码:
public <T extends ParentException> T managedException(Exception cause) {
if(ExceptionA.class.isInstance(cause)) {
return ExceptionA.class.cast(cause);
} else if(ExceptionB.class.isInstance(cause)) {
return ExceptionB.class.cast(cause);
} else if(ExceptionC.class.isInstance(cause)){
return ExceptionC.class.cast(cause);
} else {
return new ExceptionD(cause.getMessage(), cause);
}
}
这里ExceptionA、ExceptionB、ExceptionC、ExceptionD 是ParentException 的子级。
编译时出现错误:
incompatible types: ExceptionA cannot be converted to T
incompatible types: ExceptionB cannot be converted to T
incompatible types: ExceptionC cannot be converted to T
incompatible types: ExceptionD cannot be converted to T
但是,如果我将代码更改为:
@SuppressWarnings("unchecked")
public <T extends ParentException> T managedException(Exception cause) {
if(ExceptionA.class.isInstance(cause)) {
return (T) ExceptionA.class.cast(cause);
} else if(ExceptionB.class.isInstance(cause)) {
return (T) ExceptionB.class.cast(cause);
} else if(ExceptionC.class.isInstance(cause)){
return (T) ExceptionC.class.cast(cause);
} else {
return (T) new ExceptionD(cause.getMessage(), cause);
}
}
它没有编译错误。
正如 SO 线程的这个答案中提到的:How do I make the method return type generic?,允许使用T 进行强制转换,并且在该线程中给出了另一个指针:Java Generics: Generic type defined as return type only。但我的问题是:当T 有界并且所有返回的对象都落入指定的范围时,为什么我需要使用类型转换?
【问题讨论】: