Annotation trong Java 8

Trong bài này, tôi sẽ giới thiệu với các bạn một số tính năng mới hỗ trợ cho Annotation trong Java 8 là Repeating annotationType Annotation.

Nếu bạn chưa biết về Annotation, hãy xem bài viết Hướng dẫn sử dụng Java Annotation trước khi tiếp tục xem nội dung tiếp theo của bài viết.

1. Repeating annotation

Annotations được giới thiệu trong phiên bản Java 5, tính năng này đã trở thành một tính năng hữu ích và được sử dụng rộng rãi. Tuy nhiên, có hạn chế là các annotation không thể khai báo nhiều hơn một lần cùng một vị trí. Java 8 đã giới thiệu tính năng Repeating annotation, nó cho phép các annotation giống nhau có thể được khai báo nhiều lần cùng một vị trí.

Ví dụ:

package com.maixuanviet.annotation;
 
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
public class RepeatingAnnotations {
 
    // 1. Declare a Repeatable Annotation Type
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Repeatable(Filters.class)
    public @interface Filter {
        String value();
    };
 
    // 2. Declare the Containing Annotation Type
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Filters {
        Filter[] value();
    }
 
    // 3. Use repeating annotations
    @Filter("filter1")
    @Filter("filter2")
    public interface Filterable {
 
    }
 
    public static void main(String[] args) {
        // 4. Retrieving Annotations via the Filter class
        Filter[] arrFilter = Filterable.class.getAnnotationsByType(Filter.class);
        for (Filter filter : arrFilter) {
            System.out.println(filter.value());
        }
 
        // Another way
        // 4. Retrieving Annotations via the Filters class
        Filters filters = Filterable.class.getAnnotation(Filters.class);
        for (Filter filter : filters.value()) {
            System.out.println(filter.value());
        }
    }
}

Ouput của chương trình trên:

filter1
filter2
filter1
filter2

Như bạn thấy trong ví dụ trên có một Annotation trên class Filter được đánh dấu @Repeatable(Filters.class). Lớp Filters chỉ nắm giữ annotation Filter, trình biên dịch Java compiler cố gắng để che giấu sự hiện diện của nó từ developer. Vì vậy, interface Filterable có chú thích Filter được định nghĩa hai lần (không đề cập tới Filters).

Ngoài ra, Reflection API cũng cung cấp phương thức mới là getAnnotationsByType() để trả về các repeating annotation. Chú ý rằng Filterable.class.getAnnotation(Filters.class) sẽ trả về instance của Filters bởi trình biên dịch.

2. Type Annotation

Trước Java 8, Annotation chỉ có thể được áp dụng cho các khai báo (class, contructor, method, …). Từ Java 8, Annotation cũng có thể được áp dụng cho bất kỳ kiểu dữ liệu nào(Type), bao gồm: new operator, type castsimplements clauses và throws clauses.

Type annotation được tạo ra để hỗ trợ phân tích, cải tiến các chương trình Java bằng cách đảm bảo kiểm tra kiểu mạnh hơn. Bạn có thể sử dụng nhiều Annotation type để kiểm tra nhiều loại lỗi khác nhau cho cùng một kiểu.

Ví dụ: bạn muốn đảm bảo rằng một biến cụ thể trong chương trình của bạn không bao giờ được gán cho NULL, tránh lỗi NullPointerException. Bạn có thể viết một Annotation để kiểm tra điều này. Sau đó, bạn sẽ sửa đổi code của mình để chú thích biến cụ thể đó, cho biết rằng nó không bao giờ được gán cho NULL.

Ví dụ: @NonNull @Size(max = 100) String str;

Khi bạn biên dịch, nếu sử dụng NonNull tại dòng lệnh, trình biên dịch sẽ in một cảnh báo nếu nó phát hiện ra một vấn đề tiềm ẩn, cho phép bạn sửa đổi mã để tránh lỗi. Sau khi bạn sửa mã để loại bỏ tất cả cảnh báo, lỗi cụ thể này sẽ không xảy ra khi thực thi chương trình.

Thực sự tôi chưa áp dụng Type Annotation nhiều trong dự án do code khá khó đọc và khó bảo trì, các bạn có hứng thú với chủ đề có thể hiểu thêm một số link sau:

Related posts:

Spring Boot - Rest Template
Java Byte Array to InputStream
Introduction to Java 8 Streams
Comparing Strings in Java
Deploy a Spring Boot WAR into a Tomcat Server
Control Structures in Java
Removing all Nulls from a List in Java
Java Program to Implement Aho-Corasick Algorithm for String Matching
Check If a File or Directory Exists in Java
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Java equals() and hashCode() Contracts
Introduction to Spring Security Expressions
Getting the Size of an Iterable in Java
Add Multiple Items to an Java ArrayList
The Difference Between Collection.stream().forEach() and Collection.forEach()
Java Program to Find a Good Feedback Edge Set in a Graph
Composition, Aggregation, and Association in Java
Java Program to Find MST (Minimum Spanning Tree) using Kruskal’s Algorithm
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
Predicate trong Java 8
Java Program to Perform Right Rotation on a Binary Search Tree
Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
Prevent Cross-Site Scripting (XSS) in a Spring Application
Guide to Spring @Autowired
Java Program to Find a Good Feedback Vertex Set
Java Program to Find Transpose of a Graph Matrix
Comparing Long Values in Java
Java Program to Implement Binary Tree
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Java Collections Interview Questions
Spring Boot - Bootstrapping