JDK中注解的底层实现

 

前提

用Java快三年了,注解算是一个常用的类型,特别是在一些框架里面会大量使用注解做组件标识、配置或者策略。但是一直没有深入去探究JDK中的注解到底是什么,底层是怎么实现了?于是参考了一些资料,做了一次稍微详细的分析。

JDK的注解描述

参考JavaSE-8里面的

注解的声明如下:

{InterfaceModifier} @ interface Identifier AnnotationTypeBody  接口修饰符 @ interface 注解标识符 注解类型的内容

其中:

既然所有注解类型的父接口都是java.lang.annotation.Annotation,那么我们可以看一下Annotation接口的文档:

public interface Annotation

The common interface extended by all annotation types. Note that an interface that manually extends this one does not define an annotation type. Also note that this interface does not itself define an annotation type. More information about annotation types can be found in section 9.6 of The Java™ Language Specification. The AnnotatedElement interface discusses compatibility concerns when evolving an annotation type from being non-repeatable to being repeatable.

Since: 1.5

JavaSE-8中的文档对Annotation的描述和JLS-9.6中差不多,不过最后指明了可重复注解的兼容性考虑的问题,可重复注解在JDK1.8中由元注解@Repeatable实现。下面基于JDK8的最后一个版本java version 1.8.0_181探究一下注解在JDK中的底层实现。

注解实现探究

我们先定义一个十分简单的Counter注解如下:

package club.throwable.annotation;  import java.lang.annotation.*;  @Retention(RetentionPolicy.RUNTIME) @Documented @Target(ElementType.TYPE) public @interface Counter {      int count() default 0; }

我们先从直接使用@Counter注解,从直观上观察@Counter实例的类型:

@Counter(count = 1) public 
                    
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信