java中的注解

java中的注解

1.介绍

首先注解的作用类似标签,对已编写的代码运行没有任何的影响,
注解的主要作用是给框架和测试时调用对应类进行实例化或者测试使用的
主要分类:

  • Java自带
    • 标准注解:@Overider、@Deprecated、@SuppressWarnings
    • 元注解(注解的注解):@Documented、@Retention、@Inherited、@Target(前三个基本上在标注时同时使用)
  • 第三方注解
    • 例如一些Spring框架使用的注解
  • 自定义注解

2.元注解说明

  1. @Documented
    在生成文档的时候,会被包含
  2. @Retention
    注解的生命周期,源码显示的RetentionPolicy.SOURCE、编译期的RetentionPolicy.CLASS、运行时候存在的RetentionPolicy.RUNTIME
  3. @Inherited
    标识性的元注解。标识当前的注解可以由子注解继承
  4. @Target
    限定该注解能标注的作用域:构造器、字段、局部变量、方法、包、参数、接口

3.自定义注解

使用@interface 关键字
格式:

public @interface Demo1 {
    String a();

    int b() default 100; //表示没有对b赋值时,它的值是100

    String value() default "some thing"; //字符型名必须是value

    String[] paths();
}

定义注解的成员变量都是使用方法类型即:在后面加小括号,default为变量属性指定默认值

3.1自定义注解注意事项

定义一个自定义的注解:

public @interface Demo1 {
    String a();

    int b() default 100; //表示没有对b赋值时,它的值是100

    String value() default "some thing"; //字符型名必须是value

    String[] paths();
}

在其他类上使用时如果只设置一个属性值且名称为value时,value可以省略

@Demo1(value = "123") //等价于 @Demo1("123")
public class Demo2 {
}

当数组元素只有一个元素也可以简写

@Demo1(paths = {"aaa"}) // 等价于  @Demo1(paths = "aaa")
public class Demo2 {
}

4.注解信息的获取

反射技术
使用Class/Method… 的 getAnnotation 方法就可以获取。
注解代码:

@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface Demo1 {
    String a() default "aaa";

    int b() default 100; //表示没有对b赋值时,它的值是100

    String value() default "some thing"; //字符型名必须是value

    String[] paths() default "bbb";
}

被标注类

@Demo1(paths = "aaa")
public class Demo2 {
    @Demo1(a = "sss")
    public void method(){}
}

测试代码

    public static void main(String[] args) throws NoSuchMethodException {
        Class<Demo2> demo2Class = Demo2.class;
        Demo1 annotation = demo2Class.getAnnotation(Demo1.class);
        System.out.println(annotation.paths());

        Method method = demo2Class.getMethod("method");
        Demo1 annotation1 = method.getAnnotation(Demo1.class);
        System.out.println(annotation1.a());


    }
}

测试结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值