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注释