Java Reference
In-Depth Information
For this to work, both the repeatable annotation and its container must have a RUNTIME
retention policy. More information about compatibility with legacy reflection methods can be
found here: http://cr.openjdk.java.net/~abuckley/8misc.pdf .
A.1.2. Type annotations
As of Java 8, annotations can be also applied to any type uses. This includes the new operator,
type casts, instanceof checks, generic type arguments, and implements and throws clauses. Here
we indicate that the variable name of type String can't be null using a @NonNull annotation:
@NonNull String name = person.getName();
Similarly, you can annotate the type of the elements in a list:
List<@NonNull Car> cars = new ArrayList<>();
Why is this interesting? Annotations on types can be useful to perform program analysis. In
these two examples, a tool could ensure that getName doesn't return null and that the elements
of the list of cars are always non-null. This can help reduce unexpected errors in your code.
Java 8 doesn't provide official annotations or a tool to use them out of the box. It provides only
the ability to use annotations on types. Luckily, a tool called the Checker framework exists,
which defines several type annotations and lets you enhance type checking using them. If you're
curious, we invite you to take a look at its tutorial: http://www.checker-framework.org . More
information about where you can use annotations in your code can be found here:
http://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.7.4 .
A.2. Generalized target-type inference
Java 8 enhances the inference of generic arguments. You're already familiar with type inference
using context information before Java 8. For example, the method empty-List in Java is defined
as follows:
static <T> List<T> emptyList();
The method emptyList is parameterized with the type parameter T. You can call it as follows to
provide an explicit type to the type parameter:
List<Car> cars = Collections.<Car>emptyList();
But Java is capable of inferring the generic argument. The following is equivalent:
 
Search WWH ::




Custom Search