Java中注解的高级用法

开发 前端
注解本身没有含义,主要作用是标记目标元素,后续拿到改标识的元数据,进行一系列的处理。注解的使用是非常广泛的,各种框架中都使用频繁,基于注解可以将很多抽象功能提取出来,通过简单 的标识来实现各种复杂的功能。

Annotation

注解(Annotation),也叫元数据。一种代码级别的说明。它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。作用分类:

  1. 编写文档:通过代码里标识的元数据生成文档【生成文档doc文档】
  2. 代码分析:通过代码里标识的元数据对代码进行分析【使用反射】
  3. 编译检查:通过代码里标识的元数据让编译器能够实现基本的编译检查【Override】

注解不会改变程序的语义,只是作为注解(标识)存在,我们可以通过反射机制编程实现对这些元数据(用来描述数据的数据)的访问

分类

  • 运行期注解 程序运行时才会被解析到的注解,一般通过反射机制来实现,很多框架中都会用到,经常会看到一个注解和一些简单的配置来实现非常复杂的功能
  • 编译期注解 一般用来解析类型元数据,根据特定注解解析并生成代码,或者生成一些描述性文件,比如properties、json等,比如为Pojo生成getter和setter方法

关键注解

@java.lang.annotation.Retention定义注解的有效时期

相关参数:RetentionPolicy.SOURCE: 编译期生效,编译器会丢弃,编译后的class文件并不包含该注解 RetentionPolicy.CLASS:  注解会被保留在class文件中,但是运行期不会生效,被JVM忽略 RetentionPolicy.RUNTIME: 注解会被保留在class文件中,并且会在运行期生效,JVM会读取

@Target定义注解作用对象,也就是注解是可以用在类、方法、参数还是其他等待

相关参数:ElementType.TYPE: 该注解只能运用到Class, Interface, enum上 ElementType.FIELD: 该注解只能运用到Field上 ElementType.METHOD: 该注解只能运用到方法上 ElementType.PARAMETER: 该注解只能作用在参数上 ElementType.CONSTRUCTOR: 该注解只能作用在构造方法上 ElementType.LOCAL_VARIABLE: 该注解作用在地变量或catch语句 ElementType.ANNOTATION_TYPE: 该注解只能作用在注解上 ElementType.PACKAGE: 该注解只能用在包上

Java中常见的内置注解:

  • @Override
  • @Deprecated
  • @SuppressWarnings

继承关系

  • @Inherited

如果某个注解上有@Inherited注解,当查找该类型的注解时,会先查找目标类型是否存在注解,如果有,直接返回;否则,继续在父类上寻找注解, 停止的条件为在父类上找到该类型的注解或者父类为Object类型。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface ClassMapper {

}

下面的示例中,如果ClassMapper没有@Inherited修饰,则返回null

Child.class.getAnnotation(ClassMapper.class);
@Slf4j
public class ExtendAnnotationTests {
    @ClassMapper
    public class Demo { }

    public class Child extends Demo{  }
}
  • 元注解(注解上的注解)

我们知道,在Spring中,注解@Service与@Component都是用来标记类,交由Spring容器管理其对应的Bean,是结果是等效的。主要是Spring将注解和元注解进行了合并

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Mapper {

}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Mapper
public @interface ClassMapper {

}

通过下面的方法可以拿到元注解,从而进行其他扩展。

public class Tests {
    @Test
    public void test(){
        ClassMapper classMapper = Demo.class.getAnnotation(ClassMapper.class);
        log.info("classMapper: {}", classMapper);
        Mapper mapper = classMapper.annotationType().getAnnotation(Mapper.class);
        log.info("mapper: {}", mapper);
    }
}

示例

示例主要针对@java.lang.annotation.Retention参数的三种情况,了解注解是生效时期:

RetentionPolicy.RUNTIME

该示例实现通过自定义注解@SystemProperty,实现为对象字段设置系统属性

  1. 定义注解@SystemProperty
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface SystemProperty {

    String value();
}
  1. 定义对象工厂

主要作用是在运行时解析注解@SystemProperty,并实现系统属性注入的逻辑。前面说到,注解的作用主要是标记,针对RetentionPolicy.RUNTIME类型的注解,一般是在运行时 通过反射实现注解标识的类、字段或方法等等元数的处理过程。

ObjectFactory是一个对象生产工厂,这样我们可以在运行期解析目标对象中的是否有@SystemProperty标识的字段,并对该字段进行值的设定,这样式该注解设计的初衷,但是 实现需要我们根据需求实现

@Slf4j
public class ObjectFactory {
    // 省略 ...
  
    public static <T> T getObject(Class<T> type, Object... args){
        Constructor<T> constructor = findTypeConstructor(type, args);
        T object = constructor.newInstance(args);
        // 通过反射找到对象中@SystemProperty的字段,并根据其设置参数将系统属性设定到该对象字段中
        processFieldAnnotations(object, type, SystemProperty.class);
        return object;
    }
    
    // 省略 ...  
}
  1. 验证
    可以查看对象中被注解标识的属性被设置上去了
@Slf4j
public class RuntimeAnnotationTests {
    @Test
    public void run(){
        Demo demo = ObjectFactory.getObject(Demo.class);
        log.info(">> result: {}", demo.user);
    }

    @Data
    public static class Demo{
        @SystemProperty("user.name")
        private String user;
    }
}

RetentionPolicy.CLASS

该示例主要实现,编译器判断通过@FinalClass注解标记的类是否为final类型

  1. 定义注解
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
@Documented
public @interface FinalClass {

}
  1. 编写AbstractProcessor的实现
@SupportedAnnotationTypes({FinalClassProcessor.FINAL_CLASS})
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@AutoService(Processor.class)
public class FinalClassProcessor extends AbstractProcessor {

    public static final String FINAL_CLASS = "com.sucl.blog.jdk.annotation.compile.FinalClass";
    
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        TypeElement annotationType = this.processingEnv.getElementUtils().getTypeElement(FINAL_CLASS);
        if( annotationType != null ){
            for (Element element : roundEnv.getElementsAnnotatedWith(annotationType)) {
                if( element instanceof TypeElement ){
                    TypeElement typeElement = (TypeElement) element;
                    if( !typeElement.getModifiers().contains(Modifier.FINAL) ){
                        String message = String.format("类【%s】必须为final类型", typeElement);
                        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message);
                    }
                }
            }
        }
        return true;
    }
}
  1. 使FinalClassProcessor生效
  • 基于google auto-service
    3.1 添加依赖
<dependency>
      <groupId>com.google.auto.service</groupId>
      <artifactId>auto-service</artifactId>
      <version>1.1.0</version>
    </dependency>

3.2 在Processor通过注解@AutoService标识

@AutoService(Processor.class)
public class FinalClassProcessor extends AbstractProcessor{}
  • 基于maven插件
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <annotationProcessors>
            <annotationProcessor>
                com.sucl.blog.jdk.annotation.compile.FinalClassProcessor
            </annotationProcessor>
        </annotationProcessors>
    </configuration>
</plugin>
  1. 验证

打包,在项目中引入该jar,定义一个类,类似下面这样,当该类没有final修饰时,通过maven install命令,可以看到控制台打印自定义的错误信息

@FinalClass
public final class ProcessorFinder {}


图片


注意

RetentionPolicy.CLASS的使用需要达打成jar包才行,不然无法再编译时处理注解

RetentionPolicy.SOURCE

定义一个注解,通过打包后的结果观察该注解的状态

  1. 定义注解
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
@Documented
public @interface System {
    
}
  1. 定义测试类,并通过@System修饰
@System
public class SystemProvider {

}
  1. 打包,借助maven-source-plugin同时将源码打包
<plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-source-plugin</artifactId>
            <version>3.2.1</version>
            <executions>
                <execution>
                    <id>attach-sources</id>
                    <goals>
                        <goal>jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
  1. 在源码包中,可以看到该注解仍然存在,但是class文件中却没有

在基于Spring Boot开发项目时,我们一般通过 @ConfigurationProperties 配合 spring-boot-configuration-processor,可以实现在项目打包时 生成一个spring-configuration-metadata.json的配置描述文件,这样在编写application.yml配置时,就会得到配置提示,其实现方式就是基于 ConfigurationMetadataAnnotationProcessor,

结束语

注解本身没有含义,主要作用是标记目标元素,后续拿到改标识的元数据,进行一系列的处理。注解的使用是非常广泛的,各种框架中都使用频繁,基于注解可以将很多抽象功能提取出来,通过简单 的标识来实现各种复杂的功能。

责任编辑:武晓燕 来源: Java技术指北
相关推荐

2023-07-26 00:32:33

注解抽象spring

2020-12-02 11:56:16

Java注解Excel

2023-04-09 23:25:30

Java注解元注解

2015-03-09 14:18:41

Java注释原则

2022-08-31 10:13:04

C语言代码

2021-07-15 06:43:12

Jackson注解用法

2022-02-20 07:28:13

Spring注解用法

2022-02-19 07:41:36

Bean注解项目

2022-07-03 08:06:40

JavaScript语言代码

2020-02-04 14:53:22

git前端小抄

2021-12-30 12:30:01

Java注解编译器

2017-03-10 10:16:37

PythonRequests库

2024-01-02 15:41:04

CythonPython语言

2021-08-10 09:57:27

JavaScriptPromise 前端

2010-09-30 16:17:13

2022-12-06 08:37:43

2023-11-23 19:27:56

2023-08-04 08:25:03

客户配置Spring

2022-03-03 07:34:31

注解容器作用域

2020-08-16 20:42:52

more命令文件Linux
点赞
收藏

51CTO技术栈公众号