【问题标题】:Unchecked / unconfirmed cast using generics multiple bounds使用泛型多个边界的未经检查/未经确认的强制转换
【发布时间】:2012-07-02 16:57:20
【问题描述】:

以下代码使用 Sonar + FindBugs 引发“未经检查/未经确认的演员表”严重违规:

1    public static <P extends ComponentContainer & AlignmentHandler> void addComponentAligned(P parent, Component child, Alignment alignment) {
2        parent.addComponent(child);
3        parent.setComponentAlignment(child, alignment);
4    }

我应该如何避免这种违规行为的任何想法?

编辑:违规在第 3 行

编辑:方法签名如下: ComponentContainer#addComponent(组件) AlignmentHandler#setComponentAlignment(Component, Alignment)

【问题讨论】:

  • 等等,有没有办法通过你正在尝试的方式在 Java 中使用多重继承?
  • 不完整。哪个语句具体导致错误?同时显示addComponent()setComponentAligment() 的定义。我们不是读心者。
  • @BlackVegetable:多接口继承,是的。
  • 好吧,我想我已经习惯了关键字 implements 了。感谢您清除它。

标签: java generics casting sonarqube findbugs


【解决方案1】:

您的源代码中没有强制转换,但在编译产生的字节码中有。在字节码中,泛型类型被擦除。 P 的擦除是它的第一个绑定,ComponentContainer。所以字节码(几乎)等价于这个字节码:

public static void addComponentAligned(ComponentContainer parent, Component child, Alignment alignment) {
    parent.addComponent(child);
    ((AlignmentHandler)parent).setComponentAlignment(child, alignment);
}

Findbugs 查看该字节码,并得出结论认为向 AlignmentHandler 的强制转换可能会失败,因为(就 findbugs 而言)该方法接受任何 ComponentContainer。

这是一个 findbugs 错误;你应该打开一个错误报告。在我看来,它就像不需要分析源代码就可以修复的东西。字节码还包含真正的(通用)类型,findbugs 应该使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多