Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unchecked / unconfirmed cast using generics multiple bounds

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)

like image 798
Roman G. Avatar asked Jul 02 '12 16:07

Roman G.


1 Answers

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.

like image 161
Wouter Coekaerts Avatar answered Sep 22 '22 00:09

Wouter Coekaerts