1. Overview
In this quick tutorial, we’ll have a look at how to use the @SuppressWarnings annotation.
2. @SuppressWarnings Annotation
Compiler warning messages are usually helpful. Sometimes warnings can get noisy, though.
Especially when we can’t or don’t want to address them:
public class Machine {
private List versions;
public void addVersion(String version) {
versions.add(version);
}
}
The compiler will issue a warning about this method. It’ll warn that we’re using a raw-typed collection. If we don’t want to fix the warning, then we can suppress it with the @SuppressWarnings annotation.
This annotation allows us to say which kinds of warnings to ignore. While warning types can vary by compiler vendor, the two most common are deprecation and unchecked.
deprecatio**n tells the compiler to ignore when we’re using a deprecated method or type.
unchecked tells the compiler to ignore when we’re using raw types.
So, in our example above, we can suppress the warning associated with our raw type usage:
public class Machine {
private List versions;
@SuppressWarnings("unchecked")
// or
@SuppressWarnings({"unchecked"})
public void addVersion(String version) {
versions.add(version);
}
}
To suppress a list of multiple warnings, we set a String array containing the corresponding warning list:
@SuppressWarnings({"unchecked", "deprecation"})
3. Conclusion
In this guide, we saw how we can use the @SuppressWarnings annotation in Java.
The full source code for the examples can be found over on GitHub.