什么是注解的解析以及如何解析注解

代码:
解析注解的案例

代码:
MyTest2(注解)
package com.itheima.day10_annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTest2 {
String value();
double aaa() default 100;
String[] bbb();
}
Demo
package com.itheima.day10_annotation;
@MyTest2(value = "蜘蛛精",aaa = 99.5,bbb = {"至尊宝","黑马"})
public class Demo {
@MyTest2(value = "孙悟空",aaa = 99.9,bbb = {"紫霞","牛夫人"})
public void test1(){
}
}
AnnotationTest2(主程序)
package com.itheima.day10_annotation;
import org.junit.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
public class AnnotationTest2 {
@Test
public void parseClass() {
Class c = Demo.class;
if (c.isAnnotationPresent(MyTest2.class)) {
MyTest2 mytest2 =
(MyTest2) c.getDeclaredAnnotation(MyTest2.class);
System.out.println(mytest2.value());
System.out.println(mytest2.aaa());
System.out.println(Arrays.toString(mytest2.bbb()));
}
}
@Test
public void parseMethod() throws Exception {
Class c = Demo.class;
Method m = c.getDeclaredMethod("test1");
if (m.isAnnotationPresent(MyTest2.class)) {
MyTest2 mytest2 =
(MyTest2) m.getDeclaredAnnotation(MyTest2.class);
System.out.println(mytest2.value());
System.out.println(mytest2.aaa());
System.out.println(Arrays.toString(mytest2.bbb()));
}
}
}

模拟Junit框架的案例

MyTest(注解)
package com.itheima.day10_annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTest {
}
AnnotationTest3(主程序)
package com.itheima.day10_annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class AnnotationTest3 {
public void test1(){
System.out.println("======test1======");
}
@MyTest
public void test2(){
System.out.println("======test2======");
}
@MyTest
public void test3(){
System.out.println("======test3======");
}
public static void main(String[] args) throws Exception {
AnnotationTest3 a = new AnnotationTest3();
Class c = AnnotationTest3.class;
Method[] methods = c.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MyTest.class)) {
method.invoke(a);
}
}
}
}
