注解_解析注解
* 在程序使用(解析)注解:獲取注解中定義的屬性值
1. 獲取注解定義的位置的對象 (Class,Method,Field)
2. 獲取指定的注解* getAnnotation(Class)//其實就是在內存中生成了一個該注解接口的子類實現對象public class ProImpl implements Pro{public String className(){return "cn.learn.annotation.Demo1";}public String methodName(){return "show";}}
3. 調用注解中的抽象方法獲取配置的屬性值
package cn.learn.annotation;import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;/*** 框架類*/@Pro(className = "cn.learn.annotation.Demo1",methodName = "show")
public class ReflectTest {public static void main(String[] args) throws Exception {/*前提:不能改變該類的任何代碼??梢詣摻ㄈ我忸惖膶ο?#xff0c;可以執行任意方法*///1.解析注解//1.1獲取該類的字節碼文件對象Class<ReflectTest> reflectTestClass = ReflectTest.class;//2.獲取上邊的注解對象//其實就是在內存中生成了一個該注解接口的子類實現對象/*public class ProImpl implements Pro{public String className(){return "cn.learn.annotation.Demo1";}public String methodName(){return "show";}}*/Pro an = reflectTestClass.getAnnotation(Pro.class);//3.調用注解對象中定義的抽象方法,獲取返回值String className = an.className();String methodName = an.methodName();System.out.println(className);System.out.println(methodName);//3.加載該類進內存Class cls = Class.forName(className);//4.創建對象Object obj = cls.newInstance();//5.獲取方法對象Method method = cls.getMethod(methodName);//6.執行方法method.invoke(obj);}
}
package cn.learn.annotation;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** 描述需要執行的類名,和方法名*/@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Pro {String className();//代表了一套規范String methodName();
}
?
總結
- 上一篇: 注解_自定义注解_元注解
- 下一篇: 注解_案例_简单的测试框架