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,实现为对象字段设置系统属性

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

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

主要作用是在运行时解析注解@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;
    }
    
    // 省略 ...  
}
  • 验证

可以查看对象中被注解标识的属性被设置上去了

@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类型

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

}
  • 编写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;
    }
}

使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>
  • 验证

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

@FinalClass
public final class ProcessorFinder {}

图片图片

注意

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

RetentionPolicy.SOURCE

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

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

}
  • 打包,借助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技术指北
相关推荐

2017-07-12 08:20:32

闪存用途企业

2018-06-26 15:00:24

Docker安全风险

2021-02-26 08:32:28

RocketMQ阿里云

2021-01-14 05:08:44

编译链接

2017-07-04 14:01:40

机房机柜

2024-03-11 10:15:29

2024-01-31 12:34:16

panic错误检测recover

2018-01-31 16:12:47

笔记本轻薄本游戏本

2017-06-16 16:16:36

库存扣减查询

2022-07-06 11:47:27

JAVAfor循环

2022-01-07 13:34:25

Java时间格式化

2013-01-15 09:41:45

编程语言

2024-02-20 08:09:51

Java 8DateUtilsDate工具类

2023-11-13 08:49:54

2017-12-21 19:38:50

润乾中间表

2022-07-26 23:43:29

编程语言开发Java

2013-01-24 09:44:44

数据库

2021-02-03 20:19:08

Istio流量网格

2021-08-19 06:53:18

开发语言Java

2021-05-03 23:41:42

微信功能知识
点赞
收藏

51CTO技术栈公众号