The following code raises a "Unchecked / unconfirmed cast" critical violation using 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
EDIT: Method signatures follow: 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
. 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.
This is a findbugs bug; 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With