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.
deprecation 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.
