1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| package ADV_0; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; public class ADVZc6 { public @interface MyInterface { String name(); int age() default 18; String[] address(); } } @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @interface MyTest { int count() default 1; } @Target({ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @interface MyTest1 { } @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @interface MyTest2 { String value(); double height() default 169.5; String[] address(); } @ADVZc6.MyInterface(name = "赵丽颖", age = 18, address = {"北京", "上海"})
class AnnotationDemo1 { @ADVZc6.MyInterface(name = "王菲", age = 52, address = {"北京", "香港"}) public static void main( String[] args ) { int a; } }
class AnnotationDemo2 { private int age; public AnnotationDemo2(){ } public static void main(String[] args) { } public void getAgeTest(){ } } class AnnotationDemo4 { public static void main(String[] args) throws Exception { AnnotationDemo4 ad = new AnnotationDemo4(); Class c = AnnotationDemo4.class; Method[] methods = c.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(MyTest.class)) { MyTest myTest = method.getDeclaredAnnotation(MyTest.class); int count = myTest.count(); for (int i = 0; i < count; i++) { method.invoke(ad); } } } } @MyTest public void test1(){ System.out.println("test1方法执行了"); } public void test2(){ System.out.println("test2方法执行了"); } @MyTest(count = 2) public void test3(){ System.out.println("test3方法执行了"); } @MyTest public void test4(){ System.out.println("test4方法执行了"); } }
|