一、注解(Annotation)
什么是注解:
Annotation其实就是代码里的特殊标记, 它用于替代配置文件,也就是说,传统方式通过配置文件告诉类如何运
行,有 了注解技术后,开发人员可以通过注解告诉类如何运行。在Java技术里注解的典型应用是:可以通过反射技术去得
到类里面的注解,以决定怎么去运行类。
三个基本注解:
@Override://限定重写父类方法, 该注解只能用于方法
@Deprecated://用于表示某个程序元素(类, 方法等)已过时
@SuppressWarnings: //抑制编译器警告.
如何定义注解:
//MyAnnotation注解
public @interface MyAnnotation {
String name(); //String类型
int age(); //基本数据类型
Class<String> aClass(); //Class类型
Person PERSON(); //枚举类型
MyChild child(); // 注解类型
String[] arr(); //以上类型的一维数组形式
}
//MyChild注解
public @interface MyChild {
String child();
}
//枚举
public enum Person {
PERSON
}
如何使用注解:
//下面写的很繁琐,有很多种调用show方法的办法,这里主要是为了演示反射获取show方法
public static void main(String[] args) throws Exception {
//获取类对象
Class<MyAnnTest> myAnnTestClass = MyAnnTest.class;
//通过类对象创建无参的构造方法
MyAnnTest myAnnTest = myAnnTestClass.newInstance();
//获取方法或者参数
Method show = myAnnTestClass.getMethod("show", new Class[]{String.class, int.class, String.class});
//获取方法中的获取注解
MyAnnotation annotation = show.getAnnotation(MyAnnotation.class);
//获取值
String name = annotation.name();
int age = annotation.age();
String sex = annotation.sex();
show.invoke(myAnnTest, name,age,sex);
}
@MyAnnotation(name="张三",age=20,sex="男") //给注解赋值
public void show(String name,int age,String sex){
System.out.println("姓名:"+name+" 年龄:"+age+" 性别:"+sex);
}