【问题标题】:Why no Unchecked Cast warning when using delegate method?为什么使用委托方法时没有 Unchecked Cast 警告?
【发布时间】: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


【解决方案1】:

尽管由于某种原因您的警告消息不一致(您应该同时收到警告),但针对您的情况的解决方法是改变:

public <T extends Ball> BallController<T> getBallController(T ball) {

public <T extends Ball> BallController<?> getBallController(T ball) {

并删除演员表:

        return (BallController<T>) getBaseballController();
        return (BallController<T>) someOtherClass.getFootballController();

喜欢:

        return getBaseballController();
        return someOtherClass.getFootballController();

【讨论】:

    猜你喜欢
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多