java注解 -- 自定义java注解

一、自定义注解的基本元素

修饰符:访问修饰符必须为public,不写默认为public

关键字:@interface

注解名称:自定义注解的名称

注解类型元素:注解类型元素是注解中内容,即自定义接口的实现部分

public @interface MyAnnotation {
    long timeout() default 1000L;
}

 二、自定义注解用到的元注解

JDK提供了四个元注解用来修饰注解:

@Documented

1.类和方法的Annotation在缺省情况下是不会出现在javadoc中的,如果使用@Documented修饰该Annotation,则表示该注解可以出现在javadoc中。

2.定义Annotation时,@Documented可有可无,若没有定义,则Annotation不会出现在Javadoc中

@Target

1.@Target用来指定Annotation的类型属性ElementType

2.定义Annotation时,@Target可有可无,若有@Target,则该Annotation只能用于它所指定的地方,若没有@Target,则该Annotation可以用于任何地方。

Target类型 描述
ElementType.TYPE 类、接口(包括注解类型)、枚举
ElementType.FIELD 属性(包括枚举中的常量)
ElementType.METHOD 方法
ElementType.PARAMETER 参数
ElementType.CONSTRUCTOR 构造函数
ElementType.LOCAL_VARIABLE 局部变量
ElementType.ANNOTATION_TYPE 注解类型
ElementType.PACKAGE
ElementType.TYPE_PARAMETER 类型变量
ElementType.TYPE_USE 应用于任何使用类型的语句中(声明语句、泛型、强制类型转换语句中的类型)

@Retention

1.@Retention用于指定Annotation的策略属性RetentionPolicy

2.定义Annotation时,@Retention可有可无,若没有@Retention,则默认是Retention.CLASS

生命周期类型 描述
RetentionPolicy.SOURCE Annotation仅存在于编译器处理期间,编译器处理完后,该Annotation就没用了
RetentionPolicy.CLASS 编译器将Annotation存储于类对应的.class文件中(默认值)
RetentionPolicy.RUNTIME 编译器将Annotation存储于class文件中,并且可由JVM读取

@Inherited

1.控制父类类上的注解能否被子类继承

2.若父类上的注解使用了@Inherited,则子类可以继承父类中的该注解

三、自定义注解及使用

 1、自定义注解

@Documented
@Target({ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation {
    String name() default "jack";
    String sex();
}

2、定义实体类Emp使用注解

@Builder
@MyAnnotation(sex = "男")
public class Emp {
    private String name;
    private String sex;

    public Emp() {
    }

    public Emp(String name, String sex) {
        this.name = name;
        this.sex = sex;
    }
}

 注意:

  自定义注解中,设置了默认值的属性在使用时可以不用定义值,但是没有设置默认值的属性必须要定义属性值

3、测试自定义注解

public class Test {
    public static void main(String[] args) {
        //获取Emp的Class对象
        Emp emp = Emp.builder().build();
        Class cls = emp.getClass();
        if(cls.isAnnotationPresent(MyAnnotation.class)) {
            System.out.println("Emp类上配置了MyAnnotation注解!");
            //获取该对象上指定的注解内容
            MyAnnotation annotation = (MyAnnotation) cls.getAnnotation(MyAnnotation.class);
            System.out.println("name:" + annotation.name());
            System.out.println("sex:" +annotation.sex());
        }else {
            System.out.println("Emp类上没有配置MyAnnotation注解!");
        }
    }
}

此处使用的各类方法详见:

猜你喜欢

转载自blog.csdn.net/YMYYZ/article/details/128779294