解析使用注解
:解析注解、获取注解的内容、调用指定的方法
package DemoTest; import java.lang.reflect.Method; //DemoTest.Demo2 包名.类名 @pro(className="DemoTest.Demo2",methodName="show") public class Test { private static final String S = null; public static void main(String[] args) throws Exception { // TODO Auto-generated method stub //1解析注解 //1.1 获取该类的字节码文件对象 Class<Test> testClass = Test.class; //2.获取上边的注解对象 //其实就是在内存中去生成了一个该注解接口的子类实现对象。 /* * * 在程序使用(解析)注解:获取注解中定义的属性值 1. 获取注解定义的位置的对象 (Class,Method,Field) 2. 获取指定的注解 * getAnnotation(Class) //其实就是在内存中生成了一个该注解接口的子类实现对象 public class ProImpl implements Pro{ public String className(){ return "cn.itcast.annotation.Demo1"; } public String methodName(){ return "show"; } } 3. 调用注解中的抽象方法获取配置的属性值 */ pro an = testClass.getAnnotation(pro.class); //就是这一句话、内存中干了上面的代码 //3.调用注解对象中的抽象方法获取返回值 String className = an.className(); String methodName = an.methodName(); //3.加载该类进内存 Class<?> cls = Class.forName(className); //4.创建对象 Object obj = cls.newInstance(); //5.获取方法对象 Method method = cls.getMethod(methodName); //6.执行方法 method.invoke(obj); } }
package DemoTest; public class Demo2 { public void show() { System.out.println("Demo2 show"); } }
package DemoTest;
public class Demo2 {
public void show()
{
System.out.println("Demo2 show");
}
}
作者:张小龙 一个不安定的程序猿