概述
对我们的程序进行标注和解释
注解和注释的区别
使用注解进行配置配置的优势
代码更加简洁,方便
格式
public @interface 注解名称 {
public 属性类型 属性名() default 默认值 ;
}
属性类型
代码演示
xxxxxxxxxxpublic @interface Anno2 {}public enum Season { SPRING,SUMMER,AUTUMN,WINTER;}public @interface Anno1 { //定义一个基本类型的属性 int a () default 23; //定义一个String类型的属性 public String name() default "itheima"; //定义一个Class类型的属性 public Class clazz() default Anno2.class; //定义一个注解类型的属性 public Anno2 anno() default ; //定义一个枚举类型的属性 public Season season() default Season.SPRING; //以上类型的一维数组 //int数组 public int[] arr() default {1,2,3,4,5}; //枚举数组 public Season[] seasons() default {Season.SPRING,Season.SUMMER}; //value。后期我们在使用注解的时候,如果我们只需要给注解的value属性赋值。 //那么value就可以省略 public String value();}//在使用注解的时候如果注解里面的属性没有指定默认值。//那么我们就需要手动给出注解属性的设置值。//@Anno1(name = "itheima")("abc")public class AnnoDemo {}注意
如果只有一个属性需要赋值,并且属性的名称是value,则value可以省略,直接定义值即可
自定义注解案例
需求
自定义一个注解@Test,用于指定类的方法上,如果某一个类的方法上使用了该注解,就执行该方法
实现步骤
代码实现
xxxxxxxxxx//表示Test这个注解的存活时间(value = RetentionPolicy.RUNTIME)public @interface Test {}public class UseTest { //没有使用Test注解 public void show(){ System.out.println("UseTest....show...."); } //使用Test注解 public void method(){ System.out.println("UseTest....method...."); } //没有使用Test注解 public void function(){ System.out.println("UseTest....function...."); }}public class AnnoDemo { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { //1.通过反射获取UseTest类的字节码文件对象 Class clazz = Class.forName("com.itheima.myanno3.UseTest"); //创建对象 UseTest useTest = (UseTest) clazz.newInstance(); //2.通过反射获取这个类里面所有的方法对象 Method[] methods = clazz.getDeclaredMethods(); //3.遍历数组,得到每一个方法对象 for (Method method : methods) { //method依次表示每一个方法对象。 //isAnnotationPresent(Class<? extends Annotation> annotationClass) //判断当前方法上是否有指定的注解。 //参数:注解的字节码文件对象 //返回值:布尔结果。 true 存在 false 不存在 if(method.isAnnotationPresent(Test.class)){ method.invoke(useTest); } } }}概述
元注解就是描述注解的注解
元注解介绍
| 元注解名 | 说明 |
|---|---|
| @Target | 指定了注解能在哪里使用 |
| @Retention | 可以理解为保留时间(生命周期) |
| @Inherited | 表示修饰的自定义注解可以被子类继承 |
| @Documented | 表示该自定义注解,会出现在API文档里面。 |
示例代码
xxxxxxxxxx({ElementType.FIELD,ElementType.TYPE,ElementType.METHOD}) //指定注解使用的位置(成员变量,类,方法)(RetentionPolicy.RUNTIME) //指定该注解的存活时间//@Inherited //指定该注解可以被继承public @interface Anno {}public class Person {}public class Student extends Person { public void show(){ System.out.println("student.......show.........."); }}public class StudentDemo { public static void main(String[] args) throws ClassNotFoundException { //获取到Student类的字节码文件对象 Class clazz = Class.forName("com.itheima.myanno4.Student"); //获取注解。 boolean result = clazz.isAnnotationPresent(Anno.class); System.out.println(result); }}