Community
Participate
Working Groups
STEPS TO REPRO: Create the following classes: public class A { @SuppressWarnings("unchecked") public B getB() { return new B<Object>(); } @SuppressWarnings("unused") public void test() { C<String> c = getB().getC(); String s = getB().toString(); } } public class B<S> { public C<String> getC() { return new C<String>(); } } public class C<T> { } OBSERVED BEHAVIOUR: I get the following warning on the line: C<String> c = getB().getC(); // A.test() method The warning is: Type safety: The expression of type C needs unchecked conversion to conform to C<String> EXPECTED BEHAVIOUR: IMHO, there should not be any type safety error: even if getB() returns a raw B type, B.getC() certainly returns a C<String>, no matter what <S> is for B. Or, if any warning should be given, I expect something about the fact that getB() returns a raw type... but in this case, I would expect to see a warning even on the following line: String s = getB().toString(); However, this could become annoying and useless, so I would prefer no warning at all in both cases...
The behavior you describe unfortunately does not match the language specification (which we do not control). Using B as a raw type indeed causes the warning to occur. The spec expects that a raw conversion is applied to all type signatures of members of B. Hence, raw form of B<S> looks like: public class B { public C getC() { return new C<String>(); } } even if C<String> did not contain any instance of <S> type parameter. Javac6 and 7 agrees with us. Closing as invalid (though you may want to pursue the argument in the language author bug database as a specification issue).
Added GenericTypeTest#1252-1253. Note: you may want to define #getB() like this instead... public B<?> getB() { return new B<Object>(); } It doesn't stricten the type contract much, and avoids the raw conversion entirely.
Verified for 3.4M5 using build I20080204-0010
Just to add that this seems to be Sun bug number 6193717: http://bugs.sun.com/view_bug.do?bug_id=6193717 It seems they don't want to fix it... Mauro.