I have stumbled upon a strange behavior that I don't understand.
I have to cast a String to a generic and it's producing a warning.
Type safety : Unchecked cast from String to T
If I add @SuppressWarnings("unchecked")
above the method declaration it works fine.
If I add it above the assignment it produces a compiler error in eclipse.
This works fine.
@SuppressWarnings("unchecked") public <T> T search(final String query){ T returnValue = null; ... if(returnValue instanceof String){ returnValue = (T) collection.getString(attrName); }
This don't work fine.
public <T> T search(final String query){ T returnValue = null; ... if(returnValue instanceof String){ @SuppressWarnings("unchecked") // Compiler error: "returnValue cannot be resolved to a type" returnValue = (T) collection.getString(attrName); }
Any idea what's causing the discrepancy between the two methods of suppressing the warning?
An unchecked warning tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.
Use of @SuppressWarnings is to suppress or ignore warnings coming from the compiler, i.e., the compiler will ignore warnings if any for that piece of code. 1. @SuppressWarnings("unchecked") public class Calculator { } - Here, it will ignore all unchecked warnings coming from that class.
@SuppressWarnings instruct the compiler to ignore or suppress, specified compiler warning in annotated element and all program elements inside that element. For example, if a class is annotated to suppress a particular warning, then a warning generated in a method inside that class will also be separated.
The @SuppressWarnings annotation disables certain compiler warnings. In this case, the warning about deprecated code ( "deprecation" ) and unused local variables or unused private methods ( "unused" ).
You can't have annotation on arbitrary expressions (yet? Maybe they'll add it later on).
You can however have annotations on local variable declarations.
So what the compiler tries to do here is to interpret returnValue
as a type (as that's the only thing that can follow an annotation inside a method body) and fails.
Putting the annotation at the declaration of returnValue
does not help in this case. You can however create a new local variable where you perform the cast in the initializer and annotate that.
@SuppressWarnings("unchecked") T string = (T) collection.getString(attrName); returnValue = string;
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