一、概念
Annotation(注解)是Java提供的一種對元程序中元素關聯(lián)信息和元數(shù)據(jù)(metadata)的途徑和方法。
Annotation(注解)本質(zhì)上是一個接口,定義在Java的java.lang.annotation包中。
在編譯時,注解的信息會被保留在字節(jié)碼中。在運行時,我們可以使用反射API來獲取注解的元數(shù)據(jù)信息。
二、四種標準元注解
2.1 @Target
用于指定被它注解的注解范圍可以應用的地方:常用取值有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
注解指定了它的應用范圍為METHOD
。這意味著我們只能在方法上應用這個注解。在MyClass
類中,我們在myMethod()
方法上應用了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
類上應用了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
類上應用了MyDocumentedAnnotation
注解,并指定了一個值。在生成的JavaDoc文檔中,可以看到這個注解的信息。
2.4 @Inherited
用于指定被它注解的注解是否可以被子類繼承。如果一個被@Inherited
注解的注解應用在一個類上,并且這個類的子類沒有應用任何注解,則子類會繼承父類的注解。
@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
注解的父類。如果在父類或超類層次結構中找到了@Deprecated
注解,則返回true
。否則,返回false
。最后,在主方法中,我們使用這個方法來檢查ChildClass
是否繼承自帶有@Deprecated
注解的ParentClass
。
三、注解處理器
注解處理器是Java編譯時的一種工具,用于處理源代碼中的注解,并根據(jù)注解生成額外的源代碼或其他文件。注解處理器可以用于實現(xiàn)許多不同的功能,例如代碼生成、代碼優(yōu)化、代碼分析、依賴注入等。
注解處理器的工作原理是在編譯時讀取源代碼中的注解,并根據(jù)注解生成額外的源代碼或其他文件。注解處理器通過Java編譯器的API來獲取源代碼和生成額外的代碼。它可以在編譯時訪問源代碼的語法樹和其他信息,并根據(jù)注解生成相應的代碼。
簡單示例(用于生成源代碼)
首先,我們需要定義一個注解。這個注解將用于標記需要生成額外代碼的位置。在這個示例中,我們將創(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";
}
}