【发布时间】:2013-09-05 15:46:56
【问题描述】:
我有一个返回控制器的通用工厂,我想在不使用 @SuppressWarnings 的情况下避免 Unchecked Cast 警告。
在下面的示例中,工厂使用两种不同的方式返回控制器。第一个 ((BallController<T>) getBaseballController();) 会导致 Unchecked Cast 警告。第二个 ((BallController<T>) someOtherClass.getFootballController();) 不会引起任何警告。
public class BallControllerFactory {
public BaseballController getBaseballController() {
return new BaseballController();
}
public <T extends Ball> BallController<T> getBallController(T ball) {
if(ball instanceof Baseball) {
return (BallController<T>) getBaseballController();
}
else if(ball instanceof Football) {
SomeOtherClass someOtherClass = new SomeOtherClass();
return (BallController<T>) someOtherClass.getFootballController();
}
//No controller found
return null;
}
}
如您所见,只需将 getXXXController 方法移至委托类,即可消除警告。这是 SomeOtherClass,只是为了让您看不出发生了什么特别的事情。
public class SomeOtherClass {
public FootballController getFootballController() {
return new FootballController();
}
}
我的问题是,为什么当我使用委托方法返回控制器时,我没有收到 Unchecked Cast 警告,但是当我使用本地方法时,我却收到了?
为了完整起见,这里是其他类的定义(都是空类)。
public class BallController<T extends Ball>
public class BaseballController extends BallController<Baseball>
public class FootballController extends BallController<Football>
public class Ball
public class Baseball extends Ball
public class Football extends Ball
【问题讨论】:
-
好吧,在我的机器上,它们都给出了未经检查的强制转换警告。这是有效的。
-
我调查了为什么你在这两种情况下都有警告,似乎它与 eclipse 错误/警告设置有关。我打开了“忽略不可避免的泛型类型问题”。也许它只在使用委托时识别不可避免的?
-
如果是 Eclipse 特有的,请添加 eclipse 标签。
-
为什么 BaseballController 扩展 BallController
?
标签: java eclipse generics inheritance