CKTIS / Java
@SuppressWarnings — suppressing compiler warnings
@SuppressWarnings suppresses selected warning categories in an annotated declaration and its contents. It neither repairs code nor guarantees type safety; use the smallest effective scope and explain the reason.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
@SuppressWarnings("unchecked")
@SuppressWarnings({"deprecation", "removal"})
@SuppressWarnings(value = {"unchecked"})@SuppressWarnings is an annotation that controls compile-time warnings. It has SOURCE retention, so it is not retained in the .class file. It does not eliminate compilation errors or runtime risks.
Its required value element has type String[]: use @SuppressWarnings("unchecked") for one name or @SuppressWarnings({"deprecation", "removal"}) for several. "unchecked" covers operations without full type checking; "deprecation" and "removal" suppress separate categories of warnings about deprecated APIs. Java SE 21 also requires recognition of "preview". Other names depend on the compiler; unknown names are ignored, although the compiler may warn about them.
The annotation covers its declaration and contained elements. Suppressions from enclosing declarations accumulate. Choose the smallest effective scope, such as a local variable rather than an entire method. In Java SE 21, @SuppressWarnings can annotate a module declaration in module-info.java, but that suppression does not extend to types in the module. The annotation’s target list does not include PACKAGE, so applying it to a package declaration in package-info.java is a compile-time error.
In the example, the cast from Object to List<String> is unchecked. Its justification comes from creating source as a list containing only a string. The annotation merely suppresses the warning: changing where the data comes from could invalidate that justification. Prefer removing the cause of a warning when possible.
Examples
import java.util.List;
public class Main {
public static void main(String[] args) {
Object source = List.of("Java");
// source is created above as a list containing only strings.
@SuppressWarnings("unchecked")
List<String> words = (List<String>) source;
System.out.println(words.get(0));
}
}Result
Java
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.