廖雪峰Java4反射与泛型-2注解-2定义注解

1.定义注解

使用@interface定义注解Annotation

  • 注解的参数类似无参数方法
  • 可以设定一个默认值(推荐)
  • 把最常用的参数命名为value(推荐)

2.元注解

2.1Target使用方式

使用@Target定义Annotation可以被应用于源码的那些位置

  • 类或接口:ElementType.TYPE
  • 字段:ElementType.FIELD
  • 方法:ElementType.METHOD
  • 构造方法:ElementType.CONSTRUCTOR
  • 方法参数:ElementType.PARAMETER
@Target({ElementType.METHOD,ElementType.FIELD})//可以传入1个或数组
    public @interface Report{
        int type() default 0;//设定默认值
        String level() default "info";
        String value() default "";//把最常用的参数命名为value
    }

2.2Retention生命周期

使用@Retention定义Annotation的声明周期:
仅编译期:Retention.SOURCE,编译器在编译时直接丢弃,不会保存到class文件中
仅class文件: Retention.CLASS,该Annotation仅存储在class文件中,不会被读取
运行期:Retention.RUNTIME,在运行期可以读取该Annotation
如果@Retention不存在,则该Annotation默认为CLASS,通常自定义的Annotation都是RUNTIME。

    @Retention(RetentionPolicy.RUNTIME)
    public @interface Report{
        int type() default 0;//设定默认值
        String level() default "info";
        String value() default "";//把最常用的参数命名为value
    }

2.3Repeatable可重复

使用@Repeatable定义Annotation是否可重复 JDK >= 1.8
Reports.java

package com.testAnno;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

//用于存储的容器注解
@Retention(RetentionPolicy.RUNTIME)
public @interface Reports {
	Report[] value();	
}

Report.java

package com.testAnno;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

//创建可重复注解
@Repeatable(Reports.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface Report {
//	String value();
	String info();
	int type();
}

TestMyReport.java

package com.testAnno;

public class TestMyReport {
	@Report(value="1")
	public void repeatble1() {}
	@Report("3")
	@Report("2")
	public void repeatable2() {}
	
}

https://jingyan.baidu.com/article/a3761b2bf05f661576f9aaf3.html

2.4使用@Inherited定义子类是否可继承父类定义的Annotation

  • 仅针对@Target为TYPE类型的Annotation
  • 仅针对class的继承
  • 对interface的继承无效
package com.reflection;
import java.lang.annotation.*;

@Inherited
@Target(ElementType.TYPE)
public @interface Report{
    int type() default 0;
    String level() default "info";
    String value() default "";
}
@Report(type=1)
class Person1{

}
class Student1 extends Person1{}

3.定义Annotation

步骤:

  • 1.用@interface定义注解
  • 2.用元注解(meta annotation)配置注解
    * Target:必须设置
    * Retention:一般设置为RUNTIME
    * 通常不必写@Inherited,@Repeatable等等
  • 3.定义注解参数和默认值
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Report{
    int type() default 0;
    String level() default "info";
    String value() default "";
}

4.总结:

  • 使用@interface定义注解
  • 可定义多个参数和默认值,核心参数使用value名称
  • 必须设置@Target来指定Annotation可以应用的范围
原文地址:https://www.cnblogs.com/csj2018/p/10403110.html