What is @SuppressWarnings annotation in java?
@SuppressWarnings annotation provides a facility to disable compilation warnings for certain parts of the program (parameter, method, type, etc.,.).Basically, warnings are good but in some cases those are inappropriate. So @SuppressWarnings annotation tells the compiler to ignore such warnings.
In java, we have many warnings like unchecked operations, unsafe operations, serial, unused, deprecation, etc.,.
We have to pass the warning type as an argument to the annotation like below:
@SuppressWarnings("unchecked")
@SuppressWarnings({"unchecked","deprecation"})@SuppressWarnings("serial")
Let us see the program where we get unchecked operations warning.
import java.util.ArrayList;
import java.util.List;
public class supresswarnings {
public static void main(String args[]) {
List words= new ArrayList();
words.add("%&^%&&^");
}
}
If we compile above we will get warning like below:
Note: supresswarnings.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
So in order to ignore these types of warnings we can use @SuppressWarnings annotations as it will suppress the compilation warnings.Now we will use the annotation:
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("unchecked")
public class supresswarnings {
public static void main(String args[]) {
List words= new ArrayList();
words.add("%&^%&&^");
}
}
Output: it will suppress the warnings
As we have used annotation it will not throw any compilation warnings.
Below are different types of warnings we can pass as an argument to the annotation.
all to suppress all warnings
boxing to suppress warnings relative to boxing/unboxing operations
cast to suppress warnings relative to cast operations
dep-ann to suppress warnings relative to deprecated annotation
deprecation to suppress warnings relative to deprecation
fallthrough to suppress warnings relative to missing breaks in switch statements
finally to suppress warnings relative to finally block that don’t return
hiding to suppress warnings relative to locals that hide variable
incomplete-switch to suppress warnings relative to missing entries in a switch statement (enum case)
nls to suppress warnings relative to non-nls string literals
null to suppress warnings relative to null analysis
restriction to suppress warnings relative to usage of discouraged or forbidden references
serial to suppress warnings relative to missing serialVersionUID field for a serializable class
static-access to suppress warnings relative to incorrect static access
synthetic-access to suppress warnings relative to unoptimized access from inner classes
unchecked to suppress warnings relative to unchecked operations
unqualified-field-access to suppress warnings relative to field access unqualified
unused to suppress warnings relative to unused code
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.