java中的注解
1.介绍
首先注解的作用类似标签,对已编写的代码运行没有任何的影响,
注解的主要作用是给框架和测试时调用对应类进行实例化或者测试使用的
主要分类:
- Java自带
- 标准注解:@Overider、@Deprecated、@SuppressWarnings
- 元注解(注解的注解):@Documented、@Retention、@Inherited、@Target(前三个基本上在标注时同时使用)
- 第三方注解
- 例如一些Spring框架使用的注解
- 自定义注解
2.元注解说明
- @Documented
在生成文档的时候,会被包含 - @Retention
注解的生命周期,源码显示的RetentionPolicy.SOURCE、编译期的RetentionPolicy.CLASS、运行时候存在的RetentionPolicy.RUNTIME - @Inherited
标识性的元注解。标识当前的注解可以由子注解继承 - @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());
}
}
测试结果: