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.SOURCEAnnotation仅存在于编译器处理期间,编译器处理完后,该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注解!");
        }
    }
}

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值