简体   繁体   English

使用泛型多个范围进行未经检查/未经确认的强制转换

[英]Unchecked / unconfirmed cast using generics multiple bounds

The following code raises a "Unchecked / unconfirmed cast" critical violation using Sonar + FindBugs: 以下代码使用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    }

Any ideas of how should I avoid this violation? 关于如何避免这种违规行为的任何想法?

EDIT: Violation is on line 3 编辑:违反是第3行

EDIT: Method signatures follow: ComponentContainer#addComponent(Component) AlignmentHandler#setComponentAlignment(Component, Alignment) 编辑:方法签名如下:ComponentContainer#addComponent(Component)AlignmentHandler#setComponentAlignment(Component,Alignment)

There is no cast in your source code, but in the bytecode resulting from compilation there is. 源代码中没有强制转换,但是编译产生的字节码中存在强制转换。 In the bytecode, the generic types are erased. 在字节码中,通用类型被删除。 The erasure for P is its first bound, ComponentContainer . P的擦除是其第一个边界ComponentContainer So the bytecode is (almost) equivalent to the bytecode of this: 因此,字节码(几乎)与此等效:

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

Findbugs looks at that bytecode, and concludes that that cast to AlignmentHandler might fail, because (as far as findbugs sees) the method accepts any ComponentContainer. Findbugs查看该字节码,并得出以下结论:强制转换为AlignmentHandler可能会失败,因为(据findbugs所知)该方法接受任何ComponentContainer。

This is a findbugs bug; 这是一个findbugs错误; you should open a bug report. 您应该打开一个错误报告。 It looks to me like something that can be fixed without needing to analyze the source code. 在我看来,不需要分析源代码就可以修复它。 The bytecode also contains the real (generic) types, and findbugs should use that. 字节码还包含实型(通用)类型,findbugs应该使用该类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM