【Java核心基礎(chǔ)知識】10 - Java注解

一、概念

Annotation(注解)是Java提供的一種對元程序中元素關(guān)聯(lián)信息和元數(shù)據(jù)(metadata)的途徑和方法。

Annotation(注解)本質(zhì)上是一個接口,定義在Java的java.lang.annotation包中。

在編譯時,注解的信息會被保留在字節(jié)碼中。在運行時,我們可以使用反射API來獲取注解的元數(shù)據(jù)信息。

二、四種標準元注解

2.1 @Target

用于指定被它注解的注解范圍可以應(yīng)用的地方:常用取值有ElementType.TYPE(類、接口、枚舉)、ElementType.FIELD(字段)、ElementType.METHOD(方法)、ElementType.PARAMETER(參數(shù))等。

@Target(ElementType.METHOD)  
@interface MyMethodAnnotation {  
    String value();  
}  
  
public class MyClass {  
    @MyMethodAnnotation("Hello World")  
    public void myMethod() {  
        // method implementation details  
    }  
}

在這個例子中,我們定義了一個名為MyMethodAnnotation的注解,并使用@Target注解指定了它的應(yīng)用范圍為METHOD。這意味著我們只能在方法上應(yīng)用這個注解。在MyClass類中,我們在myMethod()方法上應(yīng)用了MyMethodAnnotation注解,并指定了一個值。

2.2 @Retention

用于指定被它注解的注解保留的時間。有三個取值:

  • RetentionPolicy.SOURCE表示注解僅在源代碼中保留,編譯后不會保留;
  • RetentionPolicy.CLASS表示注解在編譯時被保留,但在運行時不會被加載到JVM中;
  • RetentionPolicy.RUNTIME表示注解在運行時被保留,并且可以通過反射機制讀取。
@Retention(RetentionPolicy.RUNTIME)  
@interface MyAnnotation {  
    String value();  
}  
  
@MyAnnotation(value = "Hello World")  
public class MyClass {  
    // class implementation details  
}  
  
public class MyClassProcessor {  
    public static void process(Class<?> clazz) {  
        MyAnnotation annotation = clazz.getAnnotation(MyAnnotation.class);  
        System.out.println("MyAnnotation value: " + annotation.value());  
    }  
}

在這個例子中,我們定義了一個名為MyAnnotation的注解,并使用@Retention注解指定了它的保留策略為RUNTIME。這意味著在運行時可以通過反射機制獲取到這個注解的信息。在MyClass類上應(yīng)用了MyAnnotation注解,并指定了一個值。在MyClassProcessor類中,我們通過反射獲取到了MyClass類上的MyAnnotation注解,并打印出了它的值。

2.3 @Documented

用于指定被它注解的注解是否會包含在JavaDoc文檔中。

@Documented  
@interface MyDocumentedAnnotation {  
    String value();  
}  
  
@MyDocumentedAnnotation("This is a documented annotation")  
public class MyClass {  
    // class implementation details  
}

在這個例子中,我們定義了一個名為MyDocumentedAnnotation的注解,并使用@Documented注解。這意味著被這個注解注解的注解會被包含在JavaDoc文檔中。在MyClass類上應(yīng)用了MyDocumentedAnnotation注解,并指定了一個值。在生成的JavaDoc文檔中,可以看到這個注解的信息。

2.4 @Inherited

用于指定被它注解的注解是否可以被子類繼承。如果一個被@Inherited注解的注解應(yīng)用在一個類上,并且這個類的子類沒有應(yīng)用任何注解,則子類會繼承父類的注解。

@Inherited不能直接用于自定義的注解,它只能用于繼承自父類的系統(tǒng)注解,如@Deprecated等。如果一個類繼承自一個帶有@Deprecated注解的父類,則該類也會繼承這個注解。可以使用反射機制來檢查一個類是否繼承自帶有@Deprecated注解的父類。

import java.lang.reflect.AnnotatedElement;  
import java.lang.reflect.Modifier;  
import java.lang.reflect.annotation.Annotation;  
  
public class ReflectionExample {  
    public static void main(String[] args) {  
        Class<?> childClass = ChildClass.class;  
        Class<?> parentClass = ParentClass.class;  
  
        if (isChildClassInheritedFromDeprecatedParent(childClass, parentClass)) {  
            System.out.println(childClass.getName() + " inherits from deprecated parent " + parentClass.getName());  
        } else {  
            System.out.println(childClass.getName() + " does not inherit from deprecated parent " + parentClass.getName());  
        }  
    }  
  
    public static boolean isChildClassInheritedFromDeprecatedParent(Class<?> childClass, Class<?> parentClass) {  
        if (parentClass.isInterface()) {  
            return false; // interfaces cannot have @Deprecated annotations  
        }  
        if (Modifier.isAbstract(parentClass.getModifiers())) {  
            return false; // abstract classes cannot have @Deprecated annotations  
        }  
        if (Modifier.isFinal(parentClass.getModifiers())) {  
            return false; // final classes cannot have @Deprecated annotations  
        }  
        if (parentClass.isAnnotationPresent(Deprecated.class)) {  
            return true; // parent class has @Deprecated annotation  
        }  
        for (Class<?> superclass : childClass.getInterfaces()) {  
            if (isChildClassInheritedFromDeprecatedParent(superclass, parentClass)) {  
                return true; // child class inherits from deprecated interface  
            }  
        }  
        return false; // no @Deprecated annotation found in parent or superclass hierarchy  
    }  
}  
  
@Deprecated  
class ParentClass {  
    // class implementation details  
}  
  
class ChildClass extends ParentClass {  
    // class implementation details  
}

在這個示例中,我們定義了一個isChildClassInheritedFromDeprecatedParent方法,它接受兩個參數(shù):子類和父類。該方法使用反射機制來檢查子類是否繼承自帶有@Deprecated注解的父類。首先,我們檢查父類是否是接口、抽象類或最終類,因為這些類型的類不能有@Deprecated注解。然后,我們檢查父類是否具有@Deprecated注解。如果父類具有@Deprecated注解,則返回true。否則,我們遞歸地在子類的接口和超類中查找是否繼承自帶有@Deprecated注解的父類。如果在父類或超類層次結(jié)構(gòu)中找到了@Deprecated注解,則返回true。否則,返回false。最后,在主方法中,我們使用這個方法來檢查ChildClass是否繼承自帶有@Deprecated注解的ParentClass

三、注解處理器

注解處理器是Java編譯時的一種工具,用于處理源代碼中的注解,并根據(jù)注解生成額外的源代碼或其他文件。注解處理器可以用于實現(xiàn)許多不同的功能,例如代碼生成、代碼優(yōu)化、代碼分析、依賴注入等。

注解處理器的工作原理是在編譯時讀取源代碼中的注解,并根據(jù)注解生成額外的源代碼或其他文件。注解處理器通過Java編譯器的API來獲取源代碼和生成額外的代碼。它可以在編譯時訪問源代碼的語法樹和其他信息,并根據(jù)注解生成相應(yīng)的代碼。

簡單示例(用于生成源代碼)

首先,我們需要定義一個注解。這個注解將用于標記需要生成額外代碼的位置。在這個示例中,我們將創(chuàng)建一個名為 GenerateCode 的注解。

import java.lang.annotation.ElementType;  
import java.lang.annotation.Retention;  
import java.lang.annotation.RetentionPolicy;  
import java.lang.annotation.Target;  
  
@Retention(RetentionPolicy.SOURCE)  
@Target(ElementType.METHOD)  
public @interface GenerateCode {  
}

接下來,我們需要創(chuàng)建一個注解處理器來處理這個注解。這個處理器將查找所有標記了 GenerateCode 注解的方法,并為每個方法生成額外的源代碼。

import javax.annotation.processing.*;  
import javax.lang.model.SourceVersion;  
import javax.lang.model.element.*;  
import javax.tools.JavaFileObject;  
import java.io.Writer;  
import java.util.Set;  
  
@SupportedAnnotationTypes("com.example.GenerateCode")  
@SupportedSourceVersion(SourceVersion.RELEASE_8)  
public class GenerateCodeProcessor extends AbstractProcessor {  
    @Override  
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {  
        for (TypeElement annotation : annotations) {  
            Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);  
            for (Element element : annotatedElements) {  
                if (element.getKind() == ElementKind.METHOD) {  
                    MethodElement method = (MethodElement) element;  
                    String className = method.getEnclosingElement().getQualifiedName().toString();  
                    String methodName = method.getSimpleName().toString();  
                    String generatedCode = generateCode(className, methodName);  
                    JavaFileObject jfo = processingEnv.getFiler().createSourceFile(className + "_Generated");  
                    try (Writer writer = jfo.openWriter()) {  
                        writer.write(generatedCode);  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }  
        return true; // no further processing of this annotation type  
    }  
  
    private String generateCode(String className, String methodName) {  
        // Generate code for the method and return it as a string. This code should be based on the className and methodName parameters.  
        // You can use any language or template engine to generate the code. This is just a placeholder.  
        return "public void " + methodName + "Generated() {\n" +  
                "    // Generated code for " + className + "." + methodName + "\n" +  
                "}\n";  
    }  
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容