注解(Annotation),用法也叫元数据。中注一种代码级别的高级说明。它是用法JDK1.5及以后版本引入的一个特性,与类、中注接口、高级枚举是用法在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。作用分类:
注解不会改变程序的语义,只是作为注解(标识)存在,我们可以通过反射机制编程实现对这些元数据(用来描述数据的数据)的访问
@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中常见的内置注解:
如果某个注解上有@Inherited注解,当查找该类型的注解时,会先查找目标类型是否存在注解,如果有,直接返回;否则,继续在父类上寻找注解, 停止的条件为在父类上找到该类型的注解或者父类为Object类型。
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@Inheritedpublic @interface ClassMapper { }
下面的示例中,如果ClassMapper没有@Inherited修饰,则返回null
Child.class.getAnnotation(ClassMapper.class);
@Slf4jpublic 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)@Mapperpublic @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参数的三种情况,了解注解是生效时期:
该示例实现通过自定义注解@SystemProperty,实现为对象字段设置系统属性
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD)@Documentedpublic @interface SystemProperty { String value();}
主要作用是在运行时解析注解@SystemProperty,并实现系统属性注入的逻辑。前面说到,注解的作用主要是标记,针对RetentionPolicy.RUNTIME类型的注解,一般是在运行时 通过反射实现注解标识的类、字段或方法等等元数的处理过程。
ObjectFactory是一个对象生产工厂,这样我们可以在运行期解析目标对象中的是否有@SystemProperty标识的字段,并对该字段进行值的设定,这样式该注解设计的初衷,但是 实现需要我们根据需求实现
@Slf4jpublic 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; } // 省略 ... }
@Slf4jpublic 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; }}
该示例主要实现,编译器判断通过@FinalClass注解标记的类是否为final类型
@Retention(RetentionPolicy.CLASS)@Target(ElementType.TYPE)@Documentedpublic @interface FinalClass { }
@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; }}
<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{ }
<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命令,可以看到控制台打印自定义的错误信息
@FinalClasspublic final class ProcessorFinder { }
注意
RetentionPolicy.CLASS的使用需要达打成jar包才行,不然无法再编译时处理注解
RetentionPolicy.SOURCE
定义一个注解,通过打包后的结果观察该注解的状态
@Retention(RetentionPolicy.SOURCE)@Target(ElementType.TYPE)@Documentedpublic @interface System { }
@Systempublic class SystemProvider { }
<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>
在基于Spring Boot开发项目时,我们一般通过 @ConfigurationProperties 配合 spring-boot-configuration-processor,可以实现在项目打包时 生成一个spring-configuration-metadata.json的配置描述文件,这样在编写application.yml配置时,就会得到配置提示,其实现方式就是基于 ConfigurationMetadataAnnotationProcessor,
注解本身没有含义,主要作用是标记目标元素,后续拿到改标识的元数据,进行一系列的处理。注解的使用是非常广泛的,各种框架中都使用频繁,基于注解可以将很多抽象功能提取出来,通过简单 的标识来实现各种复杂的功能。
责任编辑:武晓燕 来源: Java技术指北 Java框架Spring(责任编辑:休闲)
iPhone 15 Pro Max中国大陆零部件仅2% 美零部件占33% -
极致轻量更迅捷 罗技G PRO X SUPERLIGHT 2游戏鼠标评测
大数据与分析正在重新定义5个行业:医学、零售、建筑、银行、交通