Java Reference
In-Depth Information
public class SuppressWarningsTest {
public void test() {
ArrayList list = new ArrayList();
list.add("Hello"); // The compiler issues an unchecked warning
}
}
Compile the SuppressWarningsTest class with an option to generate an unchecked warning using the command
javac -Xlint:unchecked SuppressWarningsTest.java
com\jdojo\annotation\SuppressWarningsTest.java:10: warning: [unchecked] unchecked call to add(E)
as a member of the raw type ArrayList
list.add("Hello"); // The compiler issues an unchecked warning
^
where E is a type-variable
E extends Object declared in class ArrayList
1 warning
As a developer, sometimes you are aware of such compiler warnings and you want to suppress them when your
code is compiled. You can do so by using a @SuppressWarnings annotation on your program element by supplying
a list of the names of the warnings to be suppressed. For example, if you use it on a class declaration, all specified
warnings will be suppressed from all methods inside that class declaration. It is recommended that you use this
annotation on the innermost program element on which you want to suppress the warnings.
The following snippet of code uses a SuppressWarnings annotation on the test() method. It specifies two
named warnings: unchecked and deprecated . The test() method does not contain code that will generate a
deprecated warning. It was included here to show you that you could suppress multiple named warnings using a
SuppressWarnings annotation. If you recompile the SuppressWarningsTest class with the same options as shown
above, it will not generate any compiler warnings.
// SuppressWarningsTest.java
package com.jdojo.annotation;
import java.util.ArrayList;
public class SuppressWarningsTest {
@SuppressWarnings({"unchecked", "deprecation"})
public void test() {
ArrayList list = new ArrayList();
list.add("Hello"); // The compiler does not issue an unchecked warning
}
}
The FunctionalInterface Annotation Type
An interface with one abstract method declaration is known as a functional interface. Previously, a functional
interface was known as SAM (Single Abstract Method) type. The compiler verifies all interfaces annotated with a
@FunctionalInterface that the interfaces really contain one and only one abstract method. A compile-time error is
generated if the interfaces annotated with this annotation are not functional interfaces. It is also a compile-time
error to use this annotation on classes, annotation types, and enums. The FunctionalInterface annotation type
is a marker interface.
 
Search WWH ::




Custom Search