【Java核心基础知识】10 - Java注解

一、概念

Annotation(注解)是Java提供的一种对元程序中元素关联信息和元数据(metadata)的途径和方法。

Annotation(注解)本质上是一个接口,定义在Java的java.lang.annotation包中。

在编译时,注解的信息会被保留在字节码中。在运行时,我们可以使用反射API来获取注解的元数据信息。

二、四种标准元注解

2.1 @Target

用于指定被它注解的注解范围可以应用的地方:常用取值有ElementType.TYPE(类、接口、枚举)、ElementType.FIELD(字段)、ElementType.METHOD(方法)、ElementType.PARAMETER(参数)等。

@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不能直接用于自定义的注解,它只能用于继承自父类的系统注解,如@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方法,它接受两个参数:子类和父类。该方法使用反射机制来检查子类是否继承自带有@Deprecated注解的父类。首先,我们检查父类是否是接口、抽象类或最终类,因为这些类型的类不能有@Deprecated注解。然后,我们检查父类是否具有@Deprecated注解。如果父类具有@Deprecated注解,则返回true。否则,我们递归地在子类的接口和超类中查找是否继承自带有@Deprecated注解的父类。如果在父类或超类层次结构中找到了@Deprecated注解,则返回true。否则,返回false。最后,在主方法中,我们使用这个方法来检查ChildClass是否继承自带有@Deprecated注解的ParentClass

三、注解处理器

注解处理器是Java编译时的一种工具,用于处理源代码中的注解,并根据注解生成额外的源代码或其他文件。注解处理器可以用于实现许多不同的功能,例如代码生成、代码优化、代码分析、依赖注入等。

注解处理器的工作原理是在编译时读取源代码中的注解,并根据注解生成额外的源代码或其他文件。注解处理器通过Java编译器的API来获取源代码和生成额外的代码。它可以在编译时访问源代码的语法树和其他信息,并根据注解生成相应的代码。

简单示例(用于生成源代码)

首先,我们需要定义一个注解。这个注解将用于标记需要生成额外代码的位置。在这个示例中,我们将创建一个名为 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 {  
}

接下来,我们需要创建一个注解处理器来处理这个注解。这个处理器将查找所有标记了 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 annotations, RoundEnvironment roundEnv) {  
        for (TypeElement annotation : annotations) {  
            Set 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";  
    }  
}

你可能感兴趣的:(【Java核心基础知识】10 - Java注解)