Java-Annotation(注解)

1、Annotation简介

在这里插入图片描述

2、系统内建的Annotation

在这里插入图片描述
2.1、@Override
在这里插入图片描述

class Student{
	String name;
	public Student(String name) {
		super();
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	//注明此方法为覆写方法的注解
	@Override
	public String toString() {
		return name;
		
	}
}
public class AnnocationTest {
	@Test
    public void annTest1() {
    	System.out.println(new Student("guai").toString());
    }
}

2.2、@Deprecated
在这里插入图片描述
在这里插入图片描述
2.3、@SuppressWarnings
在这里插入图片描述
在这里插入图片描述
例:
在这里插入图片描述

3、自定义Annotation注解

3.1、Annotation的定义格式
在这里插入图片描述
例子:

//1、定义简单的注解
//使用@interface定义接口 相当于该接口继承了java.lang.annotation.Annotation接口
@interface MyAnno{
	//在定义变量时必须在变量名后加() 当设置了属性后再使用该书解释就必须为属性设置内容
	//当然为了方便使用,可以为属性设置默认值
	public String name() default "guai";
}
@MyAnno(name="guai")

//2、使用枚举限制自定义注解中属性的取值
enum MyName{
	GUAI,SHUAI,CABBAGE;
}
@interface MyAnno1{
	//枚举类型的属性
	public MyName name() default MyName.GUAI;
}
@MyAnno1(name=MyName.SHUAI)

3.2、Retention和RetentionPolicy
在这里插入图片描述
在这里插入图片描述
3.3、通过反射取得Annotation
在这里插入图片描述
测试练习:

/**
 * 
 * @description: 反射与注解的结合应用
 * @author: guai
 * @data: 2020年3月12日 下午2:28:28
 */

class Name{
	String name;
	
	@SuppressWarnings("unchecked")
	@Deprecated
	@Override
	public String toString() {
		return "hello";
	}
}
public class ReflectAndAnno {
	//1、取得某个方法使用的全部注解
	@Test
	public void test1() throws ClassNotFoundException, NoSuchMethodException, SecurityException {
		Class<?> class1=null;
		//取得Class实例
		class1=Class.forName("com.shuai.ChapterSixteen.Name");
		//取得指定方法
		Method met=class1.getMethod("toString");
		//取得全部的注解
		System.out.println("取出全部注解(只有RUNTIME声明的才可以在运行时被取出)");
		Annotation ann[]=met.getAnnotations();
		for (Annotation annotation : ann) {
			System.out.println(annotation);
		}
		
		//取得指定的注解
		System.out.println("取得指定注解");
		Annotation ann1=met.getAnnotation(Deprecated.class);
		System.out.println(ann1);
	}
}

3.4、@Target注解
通过@Target注解可以为注解指定使用位置如只能在注释上使用,或只能在类、接口等指定位置声明使用
在这里插入图片描述
在这里插入图片描述
3.5、Inherited注释
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值