Skip to main content

Command Palette

Search for a command to run...

Bài 2: Tạo Annotation Tùy Chỉnh trong Java

Published
3 min readView as Markdown

1. Tạo Annotation Cơ Bản

Annotation tùy chỉnh cho phép bạn thêm metadata vào mã nguồn theo cách phù hợp với nhu cầu cụ thể của bạn. Đây là bước cơ bản để khai báo một Annotation tùy chỉnh.

1.1. Khai báo Annotation tùy chỉnh

Annotation được khai báo giống như khai báo một interface, nhưng với từ khóa @interface.

Ví dụ:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
    String value();
}
1.2. Sử dụng Annotation tùy chỉnh

Sau khi khai báo, bạn có thể sử dụng Annotation này trên các phần tử như lớp, phương thức, hoặc biến.

Ví dụ:

public class MyClass {
    @MyAnnotation(value = "Hello, World!")
    public void myMethod() {
        System.out.println("This is my method");
    }
}

2. Element trong Annotation

Element trong Annotation giống như các thuộc tính của một đối tượng, chúng ta có thể khai báo các element với các kiểu dữ liệu khác nhau như kiểu nguyên thủy, chuỗi, lớp, hoặc thậm chí là một Annotation khác.

2.1. Khai báo element

Element được khai báo giống như phương thức trong interface, với kiểu dữ liệu trả về xác định kiểu của element.

Ví dụ:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
    String value();
    int number() default 0;
}
2.2. Sử dụng element

Khi sử dụng Annotation, bạn có thể gán giá trị cho các element.

Ví dụ:

public class MyClass {
    @MyAnnotation(value = "Hello, World!", number = 42)
    public void myMethod() {
        System.out.println("This is my method");
    }
}

3. Meta-annotations

Meta-annotations là các Annotation áp dụng cho Annotation khác để xác định hành vi của chúng. Các meta-annotations phổ biến bao gồm:

3.1. @Target

@Target xác định các loại phần tử mà một Annotation có thể áp dụng (ví dụ: phương thức, lớp, biến).

Ví dụ:

@Target(ElementType.METHOD)
public @interface MyAnnotation {
    String value();
}
3.2. @Retention

@Retention xác định thời điểm Annotation được giữ lại (ví dụ: runtime, compile-time).

Ví dụ:

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value();
}
3.3. @Documented

@Documented chỉ ra rằng Annotation này nên được bao gồm trong tài liệu Javadoc.

Ví dụ:

@Documented
public @interface MyAnnotation {
    String value();
}
3.4. @Inherited

@Inherited cho phép Annotation của một lớp cha được kế thừa bởi các lớp con.

Ví dụ:

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value();
}

4. Ví dụ Tổng hợp

Kết hợp tất cả các kiến thức trên để tạo và sử dụng một Annotation tùy chỉnh phức tạp hơn.

4.1. Khai báo Annotation
import java.lang.annotation.*;

@Documented
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value();
    int number() default 0;
    String[] tags() default {};
}
4.2. Sử dụng Annotation
public class MyClass {
    @MyAnnotation(value = "Example Method", number = 5, tags = {"example", "test"})
    public void exampleMethod() {
        System.out.println("This is an example method");
    }
}
4.3. Đọc Annotation trong Runtime

Sử dụng Reflection để đọc và xử lý Annotation trong thời gian chạy.

import java.lang.reflect.Method;

public class AnnotationProcessor {
    public static void main(String[] args) throws Exception {
        Method method = MyClass.class.getMethod("exampleMethod");

        if (method.isAnnotationPresent(MyAnnotation.class)) {
            MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
            System.out.println("Value: " + annotation.value());
            System.out.println("Number: " + annotation.number());
            System.out.print("Tags: ");
            for (String tag : annotation.tags()) {
                System.out.print(tag + " ");
            }
        }
    }
}

Tổng kết

Trong bài viết này, chúng ta đã học cách tạo và sử dụng Annotation tùy chỉnh trong Java. Chúng ta đã xem xét các thành phần của Annotation, cách khai báo và sử dụng chúng, và các meta-annotations quan trọng. Bài viết cũng đã cung cấp một ví dụ tổng hợp để minh họa cách sử dụng Annotation tùy chỉnh trong thực tế. Trong bài viết tiếp theo, chúng ta sẽ tìm hiểu cách sử dụng Annotation trong lập trình AOP (Aspect-Oriented Programming) với Spring Framework.

More from this blog

devngu

169 posts