我遵循了下面的代码片段:
这里的
编译时,我收到了以下错误:
但是,如果我将代码更改为:
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线程的这个答案中所提到的:如何使方法返回类型通用?,使用T
进行强制转换是允许的,另一个指针在这个线程中给出:Java泛型:仅将通用类型定义为返回类型。但我的问题是:当T
被限定并且所有返回对象都落在指定的范围内时,为什么需要使用类型转换?
managedException()
中提出的代码可以编译,但是无济于事:你将其转换为特定类型,但该方法返回父类型。 - davidxxxreturn cause instanceof ParentException ? (ParentException) cause : new ExceptionD(cause.getMessage(), cause);
- Lii