自定义注解

Custom nnotation

标签(空格分隔): Java注解


1. The concept of annotation

  • An annotation is a form of metadata, that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Annotations have no direct effect on the operation of the code they annotate.

We can draw the following conclusions from the official description:

  1. An annotation is a form of metadata, just like class ,interface ,array ,enumerate .
  2. Annotations are used to modify classes, methods, variables, parameters, packages.
  3. Annotations have no direct effect on the operation of the code they annotate.

2. How to customize annotations

  • An annotation is simply a tag that can be stamped on key points in program code (classes, methods, variables, parameters, packages) and then detected at compile time or run time to perform special operations.So we can see the basic flow of custom annotation usage:
  1. Customize annotations --- Equivalent to definition mark
  2. Configuration annotations --- Place the tag on top of the program code you need to use
  3. Parse annotations --- tags are detected at compile time or run time and special operations are performed.
/**
 * 使用@interface定义注解 --- 相当于定义标记
 * 配置注解们 @Target: 限定某个自定义注解能过被应用在那些Java元素上面,具体的限定范围在 Element的枚举类当中. @Retention: 注解的生命周期有三个阶段: 1. Java源文件阶段 2. 编译到class文件阶段 3. 运行期阶段.
 * 同样使用了RetentionPolicy枚举类型定义了三个阶段.
 * 1. 如果一个注解被定义为RetentionPolicy.SOURCE, 则它被限定在Java源文件当中, name这个注解既不会参与编译也不会在运行期起任何作用, 这个注解就和一个注释是一样的效果, 只能被阅读Java文件的人看到. --- 没吊用 ?
 * 2. 如果一个注解被定义为RetentionPolicy.CLASS, 则他被编译到Class文件中, 那么编译器可以在编译时根据注解做一些处理动作, 但是运行JVM(Java虚拟机)会忽略它, 我们运行期也不能读取到.
 * 3. 如果一个注解被定义为RetentionPolicy.RUNTIME, 那么这个注解可以在运行期的加载阶段会被加载到Class对象中. 那么在程序运行阶段, 我们呢可以通过反射得到这个注解, 并且通过判断是否有这个注解或这个注解中属性的值, 从而执行不同的程序代码段. 我们实际开发中的自定义注解几乎都是使用的RetentionPolicy.RUNTIME
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE,ElementType.METHOD})
@interface Xpower{
    String name();
    int age() default 11;
    int[] score();
}

3. 自定义注解的场景与实现

  • 登录,权限拦截,日志处理,以及各种Java框架.如: Spring,Hibernate,JUnit提到注解就不能不说反射,Java自定义注解是通过运行时靠反射获取注解. 在实际开发中, 例如我们需要获取某个方法的调用日志, 我们就可以通过AOP(动态代理)给方法添加上切面, 通过反射开获取方法包含的注解,如果包含日志注解,就进行日志记录.反射的实现在Java应用层面上来讲,是通过对Class对象的操作实现的,Class对象为我们提供了一系列方法对类进行操作. 在JVM这个角度来说, Class文件是一组以8位字节为基础单位的二进制流,各个数据项目按照严格的顺序紧凑的排列在Class文件中里面包含了类,方法,字段等等相关的数据, 通过对Class数据流的处理我们即可得到字段,方法等数据.

原文地址:https://www.cnblogs.com/A-FM/p/11558388.html