文章目录
- 前言
- Annotation包
- 自定义注解
- 自定义注解示例
参考文章:java 自定义注解 用处_java注解和自定义注解的简单使用
参考文章:java中自定义注解的作用和写法
前言
在使用Spring Boot的时候,大量使用注解的语法去替代XML配置文件,十分好用。
然而,在使用注解的时候只知道使用,却不知道原理。直到需要用到自定义注解的时候,才发现对注解原理一无所知,所以要学习一下。
Annotation包
Java类库中提供了java.lang.annotation包,包中包含了元注解和接口,定义自定义注解所需要的所有内容都在这个包中。
 
 四个常用的元注解:负责注解其他注解
- @Target:用于描述注解的使用范围:接口、类、枚举等等
- @Retention:表示在”source、class、runtime“哪个阶段,注解依然存在
- @Documented:说明该注解将被包含在javadoc中
- @Inherited:说明子类可以继承父类中的该注解
自定义注解
- 使用@interface关键字来自定义注解时,自动继承java.lang.annotation.Annotation接口(隐式继承),由编译程序自动完成其它细节。在定义注解时,不能显式继承其它的注解或接口。
- @interface关键字用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数。
- 方法的名称就是参数的名称,返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum),可以通过default来声明参数的默认值。
/*
	public @interface 注解名{
		访问修饰符 返回值类型 参数名() default 默认值;
	}
*/
	public @interface MyAnnotation {
		String name()default ""; //姓名,默认值空字符串
		String sex()default "男"; //性别,默认值男
	}
}
- 支持的返回类型
- 所有基本数据类型(int,float,boolean,byte,double,char,long,short)
- String类型
- Class类型
- enum类型
- Annotation类型
- 以上所有类型的数组
自定义注解示例
自定义注解
	public @interface MyAnnotation {
		String name()default ""; //姓名,默认值空字符串
		String sex()default "男"; //性别,默认值男
	}
将注解使用在类和方法上
//将注解使用在类上
@MyAnnotation(name = "谢小猫")
public class MyAnnotationOnClass{	
}
public class MyAnnotationOnMethod{
	
	//将注解使用在方法上
	@MyAnnotation(name= "赵小虾")
	public voidzhaoShrimp() {
	
	}
	
	//将注解使用在方法上
	@MyAnnotation(name= "李小猪", sex = "女")
	public voidliPig() {
	
	}
}
通过反射获取注解信息并打印出来
public class MyAnnotationTest {
	public static voidmain(String[] args) {
		//通过反射机制MyAnnotationOnClass.class,判断是否含有MyAnnotation注解
		if (MyAnnotationOnClass.class.isAnnotationPresent(MyAnnotation.class)) {	
		
		//返回指定注解
		MyAnnotation myAnnotation = MyAnnotationOnClass.class.getAnnotation(MyAnnotation.class);
		//完整注解:@com.yanggb.anntation.MyAnnotation(name=谢小猫,sex=男)
		System.out.println("完整注解:" +myAnnotation);
		//性别:男
		System.out.println("性别:" +myAnnotation.sex());
		//姓名:谢小猫
		System.out.println("姓名:" +myAnnotation.name());
		
		System.out.println("---------------------------------------------------------");
	}
	
	//通过反射机制获取所有方法
	Method[] methods = MyAnnotationOnMethod.class.getDeclaredMethods();
	for(Method method : methods) {
		System.out.println("方法声明:" +method);
		
		if (method.isAnnotationPresent(MyAnnotation.class)) {
			MyAnnotation myAnnotationInMethod= method.getAnnotation(MyAnnotation.class);
			System.out.println(
								"方法名:" +method.getName()+
								 ",姓名:" +myAnnotationInMethod.name()+ 
								 ",性别:" + myAnnotationInMethod.sex() + 
								 ")"
								);
		}
	}
}






![[软件工程导论(第六版)]第3章 需求分析(课后习题详解)](https://img-blog.csdnimg.cn/4c778e1d5cb54e648742e2fea5fe8afc.png)













