While working with Lambdas and generics, I encountered a special case of unsafe cast warnings.
During reproducing and making an SSCCE, I found that it is probably related to the fact that the lambda is effectively "inside" the return statement.
The question is: Why do I get a warning in the warningUnnecessarySuppressWarnings
method?. When removing @SuppressWarnings("unchecked")
, I get:
Type safety: Unchecked cast from List to List
As shown in the warningUnsafeCast
method. Because of this, the annotation is not unnecessary as the new warning says.
I am using Eclipse Kepler SP2 for Java EE Developers, with Build id: 20140224-0627
Also using the recommended update-site for Java 8 support in Eclipse Kepler
public static void main(String[] args) {
System.out.println(warningUnnecessarySuppressWarnings());
System.out.println(warningUnsafeCast());
System.out.println(withoutWarning());
}
private static Integer perform(Function<List<?>, Integer> func) {
return func.apply(Arrays.asList("a", "b", "c"));
}
private static Integer warningUnnecessarySuppressWarnings() {
return perform(list -> {
@SuppressWarnings("unchecked") // Unnecessary @SuppressWarnings("unchecked")
List<String> unsafeCast = (List<String>) list;
return unsafeCast.size();
});
}
private static Integer warningUnsafeCast() {
return perform(list -> {
List<String> unsafeCast = (List<String>) list; // Type safety: Unchecked cast from List<capture#4-of ?> to List<String>
return unsafeCast.size();
});
}
@SuppressWarnings("unchecked")
private static Integer withoutWarning() {
return perform(list -> {
List<String> unsafeCast = (List<String>) list;
return unsafeCast.size();
});
}
What Does the “unchecked cast” Warning Mean? The “unchecked cast” is a compile-time warning. Simply put, we'll see this warning when casting a raw type to a parameterized type without type checking. An example can explain it straightforwardly.
@SuppressWarnings("unchecked") is used when Java generics just don't let you do what you want to, and thus, you need to explicitly specify to the compiler that whatever you are doing is legal and can be executed at the time of execution.
I think @suppress(“UNCHECKED_CAST”) is what you're after. It can be applied at various levels (statement, method, etc). Indeed, thanks Andrew. I also found Kotlin's version of this annotation: @suppress (should probably be capitalized).
The code in question is type-unsafe and therefore should generate a warning. The @SuppressWarnings
annotation is of course necessary to suppress this warning.
It is apparently a bug in Eclipse Kepler SP2 that it issues a warning for the statement, but then warns that @SuppressWarnings
is unnecessary when the annotation is added.
The workaround is to disable the "unnecessary @SuppressWarning
" warning in the Eclipse compiler configuration.
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