做ic什么网站好,wordpress 设置站点地址,洛阳手机网站开发,建造师官网查询系统注解解析与应用场景
1.注解解析
注解解析就是判断类上、方法上、成员变量上是否存在注解#xff0c;并把注解里的内容给解析出来
2.如何解析注解#xff1f;
思想#xff1a;要解析谁上面的注解#xff0c;就应该先拿到谁#xff08;通过反射#xff09;如果要解析类…注解解析与应用场景
1.注解解析
注解解析就是判断类上、方法上、成员变量上是否存在注解并把注解里的内容给解析出来
2.如何解析注解
思想要解析谁上面的注解就应该先拿到谁通过反射如果要解析类上面的注解则应该先获取该类的Class对象再通过Class对象解析其上面的注解如果要解析成员方法上的注解则应该获取到该成员方法的Method对象再通过Method对象解析其上面的注解Class、Method、Field、Constructor都实现了AnnotatedElement接口它们都拥有解析注解的能力
AnnotatedElement接口提供了解析注解的方法说明public Annotation[] getDeclaredAnnotaions()获取当前对象上面的注释public T getDeclaredAnnotaion(Class T annotationClass)获取指定的注解对象public boolean isAnnotationPresent(Class Annotation annotationClass)判断当前对象上是否存在某个注解
public class MyAnnotationTest{Testpublic void parseMethod() throws Exception { //解析方法上的注解//获取Class对象Class clazz Demo.class;//获取Method对象Method method clazz.getDeclaredMethod(test);//判断Method对象上是否包含MyAnnotation注解if(method.isAnnotationPresent(MyAnnotation.class)){//获取指定的注解对象MyAnnotation myAnnotation (MyAnnotation) method.getDeclaredAnnotation(MyAnnotation.class);//强转后打印信息System.out.println(myAnnotation.value()); //李四System.out.println(myAnnotation.age()); //28System.out.println(myAnnotation.address()); //北京}}Testpublic void parseClass(){ //解析类上的注解//获取Class对象Class clazz Demo.class;//判断Class对象上是否包含MyAnnotation注解if(clazz.isAnnotationPresent(MyAnnotation.class)){//获取指定的注解对象MyAnnotation myAnnotation (MyAnnotation) clazz.getDeclaredAnnotation(MyAnnotation.class);//强转后打印信息System.out.println(myAnnotation.value()); //张三System.out.println(myAnnotation.age()); //20System.out.println(myAnnotation.address()); //西安}}
}/*定义Demo类并使用定义注解MyAnnotation修饰属性值自拟*/
MyAnnotation(value 张三, age 20, address 西安)
class Demo {//Demo类中定义test方法并使用定义注解MyAnnotation修饰属性值自拟MyAnnotation(value 李四, age 28, address 北京)public void test(){}
}Target({ElementType.TYPE, ElementType.METHOD}) //类和成员方法上
Retention(RetentionPolicy.RUNTIME) //保留到运行阶段
interface MyAnnotation {String value();int age() default 18;String address();
}3.应用场景
模拟Junit程序提供main方法运行后能自动触发加了MyTest注解的所有方法
需求定义若干个方法只要加了MyTest注解就会触发该方法执行
分析
定义一个自定义注解MyTest只能标注在方法上存活范围一直都在定义若干个方法部分方法加上MyTest注解修饰部分方法不加模拟一个Junit程序可以触发加了MyTest注解的方法执行
public class Demo {public static void main(String[] args) throws Exception {//获取Demo类的Class对象Class clazz Demo.class;//获取所有Method对象Method[] methods clazz.getDeclaredMethods();//遍历获取每一个Method对象for (Method method : methods) {//方法上如果声明了MyTest注解if (method.isAnnotationPresent(MyTest.class)) {//运行该方法参数是空参构造创建的对象method.invoke(clazz.getConstructor().newInstance());}}}//2、定义若干个方法在想执行的方法上声明MyTest注解public void test1() {System.out.println(test1执行了...);}MyTestpublic void test2() {System.out.println(test2执行了...);}public void test3() {System.out.println(test3执行了...);}MyTestpublic void test4() {System.out.println(test4执行了...);}
}//1、自定义注解MyTest只能注解方法存活范围直到RUNTIME
Retention(RetentionPolicy.RUNTIME)
Target(ElementType.METHOD)
interface MyTest {}