JavaWeb1.3.3【基礎加強:註解案例(註解+反射重構"JavaWeb-1.2.3【基礎加強:案例(反射+配置檔案)】)】
阿新 • • 發佈:2021-06-23
1 package com.yubaby.annotation.p2; 2 3 /* 4 * 在程式使用(解析)註解:獲取註解中定義的屬性值 5 1. 獲取註解定義的位置的物件 (Class,Method,Field) 6 2. 獲取指定的註解 7 * getAnnotation(Class) 8 //其實就是在記憶體中生成了一個該註解介面的子類實現物件 9 10 public class ProImpl implements Pro{ 11 public String className(){12 return "cn.itcast.annotation.Demo1"; 13 } 14 public String methodName(){ 15 return "show"; 16 } 17 } 18 3. 呼叫註解中的抽象方法獲取配置的屬性值 19 20 利用註解重構"JavaWeb-1.2.3【基礎加強:案例(反射+配置檔案)】"21 對此案例,相較於利用配置檔案,利用註解實現可以簡化 22 */ 23 24 import java.lang.reflect.Method; 25 26 /** 27 * 框架類 28 */ 29 30 @Pro(className = "com.yubaby.annotation.p2.Dog", methodName = "eat") 31 public class ReflectTest { 32 public static void main(String[] args) throws Exception{ 33 //解析註解 34 35 //1 獲取本類的位元組碼檔案物件 36 Class<ReflectTest> reflectTestClass = ReflectTest.class; 37 38 //2 獲取註解物件 39 Pro annotation = reflectTestClass.getAnnotation(Pro.class); 40 /* 41 其實就是在記憶體中生成了一個該註解介面的子類實現物件 42 public class ProImpl implements Pro{ 43 public String className(){ 44 return "com.yubaby.annotation.p2.Dog"; 45 } 46 public String methodName(){ 47 return "eat"; 48 } 49 50 } 51 */ 52 53 //3 呼叫註解物件中定義的抽象方法(又稱屬性),獲取返回值 54 String className = annotation.className(); 55 String methodName = annotation.methodName(); 56 // System.out.println(className); //com.yubaby.annotation.p2.Dog 57 // System.out.println(methodName); //eat 58 59 //4.載入該類進記憶體 60 Class cls = Class.forName(className); 61 62 //5.建立物件 63 Object obj = cls.getDeclaredConstructor().newInstance(); //類物件 64 Method method = cls.getMethod(methodName); //方法物件 65 66 //6.執行方法 67 method.invoke(obj); //狗吃狗糧 68 } 69 }
1 package com.yubaby.annotation.p2; 2 3 import java.lang.annotation.ElementType; 4 import java.lang.annotation.Retention; 5 import java.lang.annotation.RetentionPolicy; 6 import java.lang.annotation.Target; 7 8 /** 9 * 代替配置檔案pro.properties 10 * 描述需要執行的類名和方法名 11 */ 12 13 @Target({ElementType.TYPE}) //希望作用與類上 14 @Retention(RetentionPolicy.RUNTIME) //希望被保留在RUNTIME階段 15 public @interface Pro { 16 String className(); 17 String methodName(); 18 }
1 package com.yubaby.annotation.p2; 2 3 public class Cat { 4 public void eat(){ 5 System.out.println("貓吃貓糧"); 6 } 7 }
1 package com.yubaby.annotation.p2; 2 3 public class Dog { 4 public void eat(){ 5 System.out.println("狗吃狗糧"); 6 } 7 }