Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 13:15:12 Viewed : 249
Java 8 introduced the concept of type annotations, which allows you to apply annotations to types, not just declarations. Type annotations are used in conjunction with the pluggable type-checking framework. Here are some key points about type annotations in Java 8:
Where Type Annotations Can Be Used:
instanceof
Operator: You can annotate the type in an instanceof
expression.Annotation Types:
@Target
specifying ElementType.TYPE_USE
or ElementType.TYPE_PARAMETER
.RetentionPolicy:
RetentionPolicy.RUNTIME
, meaning they are available for reflection at runtime.Common Annotations for Type Annotations:
@NonNull
: Indicates that a variable or parameter cannot be null
.@Nullable
: Indicates that a variable or parameter can be null
.@ReadOnly
: Suggests that a variable is used in a read-only context.Example:
javaimport java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface NonNull {}
Using the @NonNull
annotation:
javaimport java.util.List;
public class Example {
public static void main(String[] args) {
List<@NonNull String> names = List.of("John", "Jane", "Bob");
String first = names.get(0); // No warning about potential null
processName(null); // Compiler warning about passing null
}
static void processName(@NonNull String name) {
// Process the non-null name
}
}
In this example, the @NonNull
annotation is used on the generic type argument in the List
and on the parameter of the processName
method.
Type annotations play a crucial role in supporting stronger type checking and expressing additional constraints on the use of types in various contexts. They are especially useful in situations where simple annotations on declarations are not sufficient.