@注解讲解,并学会自己定义注解


参考文章: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 "男"; //性别,默认值男
	}
}
  1. 支持的返回类型
  • 所有基本数据类型(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() + 
								 ")"
								);
		}
	}
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值