Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

@SuppressWarnings

Turns off chosen compiler warnings for a class, method or variable.

Available since: Java 5

Syntax

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, MODULE}) @Retention(SOURCE) public @interface SuppressWarnings

Parameters

ParameterTypeDescription
valueString[]Warning names: unchecked, deprecation, removal, rawtypes and others.

Examples

An unchecked cast to List<String> produces a warning:

List<String> names(Object data) {
    return (List<String>) data;
}
 
void main() {
    IO.println(names(List.of("Anna", "Oleg")));
}

Output:

Main.java:2: warning: [unchecked] unchecked cast
    return (List<String>) data;
                          ^
  required: List<String>
  found:    Object
1 warning
[Anna, Oleg]

With the annotation on the method there is no warning:

@SuppressWarnings("unchecked")
List<String> names(Object data) {
    return (List<String>) data;
}
 
void main() {
    IO.println(names(List.of("Anna", "Oleg")));
}

Output:

[Anna, Oleg]

Notes

Put the annotation as close to the problem as possible — on a variable or method, not on the whole class — and only when you are sure the code is safe. Several values are passed as an array: @SuppressWarnings({"unchecked", "rawtypes"}). The set of supported names depends on the compiler and IDE; javac understands the same ones as the -Xlint option.

See also

  • @Deprecated — Marks an outdated class, method or field. The compiler warns when they are used.
  • @Override — Marks a method that overrides a method of a parent class or interface. The compiler checks that it really does.
  • var — Declares a local variable whose type the compiler infers from the value.

In the tutorial

  • Annotations — Annotations in Java — @Override, @Deprecated, @FunctionalInterface, @SuppressWarnings, declaring your own annotation, @Retention, @Target and reading annotations at run time.

Thanks for reading!

Donate to the site — we work hard for you.