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

使用@interface定义注解Annotation

  • 注解的参数类似无参数方法
  • 可以设定一个默认值(推荐)
  • 把最常用的参数命名为value(推荐)
    元注解
    使用@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
    }

使用@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
    }

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

import java.lang.annotation.*;
@Repeatable//报错,提示‘value’ missing though required
@Target(ElementType.TYPE)
public @interface Report{
    int type() default 0;//设定默认值
    String level() default "info";
    String value() default "";//把最常用的参数命名为value
}
@Report(type=1,level="debug")
@Report(type=2,level="warning")
public class Main{
}

使用@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{}

定义Annotation的步骤:

  • 用@interface定义注解
  • 用元注解(meta annotation)配置注解
    * Target:必须设置
    * Retention:一般设置为RUNTIME
    * 通常不必写@Inherited,@Repeatable等等
  • 定义注解参数和默认值
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 "";
}

猜你喜欢

转载自www.cnblogs.com/csj2018/p/10403110.html