彻底搞定注解2---通过Class和Method获取注解及参数

如题所述

第1个回答  2022-07-11
getAnnotation:返回指定的注解

isAnnotationPresent:判定当前元素是否被指定注解修饰

getAnnotations:返回所有的注解

getDeclaredAnnotation:返回本元素的指定注解

getDeclaredAnnotations:返回本元素的所有注解,不包含父类继承而来的

定义一个注解 

/**

* 自定义个一个注解

*/

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.TYPE, ElementType.METHOD})

@Documented

public @interface MyDef {

String name()default "";

@AliasFor("value11")

String[] path()default {};

String value()default "";

}

通过class获取注解及参数,(method获取注解的方式和Class类似)

@MyDef(name ="ssss",value ="sad",path ="pppp")

@Component

public class MyAnnoM {

@MyDef(value ="sad")

public void doSomething(){

       System.out.println("实现一个注解。。");

}

public static void main(String args[])throws NoSuchMethodException {

        //通过Class获取注解

        Class cla = MyAnnoM.class;

        Annotation annotation = cla.getAnnotation(Component.class);//获取指定注解

        Annotation[] annotations = cla.getAnnotations();//返回所有的注解

        boolean annotationPresent = cla.isAnnotationPresent(Component.class);//判定当前元素是否被指定注解修饰

        Annotation[] declaredAnnotations = cla.getDeclaredAnnotations();//返回本元素的指定注解

        Annotation declaredAnnotation = cla.getDeclaredAnnotation(Component.class);//返回本元素的所有注解,不包含父类继承而来的

        System.out.println("annotation:"+annotation);

        System.out.println("annotations:"+annotations[0]+annotations[1]);

        System.out.println("annotationPresent:"+annotationPresent);

        System.out.println("declaredAnnotations:"+declaredAnnotations[0]+declaredAnnotations[1]);

        System.out.println("declaredAnnotation:"+declaredAnnotation);

        new MyAnnoM().getss();

}

public void getss(){

        MyDef annotation = getClass().getAnnotation(MyDef.class);

        System.out.println("name"+annotation.name());//可以获取相应的注解,并取得其参数

        System.out.println("value"+annotation.value());

        System.out.println("path"+annotation.path());

}

}