package com.reflect.test; public class Demo1 { public void method(){ System.out.println("Demo1...method"); } }
package com.reflect.test; 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(); }
package com.reflect.test; import java.lang.reflect.Method; @pro(className = "com.reflect.test.Demo1",methodName = "method") public class ReflectTest { public static void main(String[] args) throws Exception{ //1.解析注解 //获取该类的字节码文件对象 Class reflectTestClass = ReflectTest.class; //获取字节码对象的注解文件 pro an = (pro) reflectTestClass.getAnnotation(pro.class); //调用注解对象中的方法 String className = an.className(); String methodName = an.methodName(); //加载该类到内存 Class cls = Class.forName(className); //创建对象 Object obj = cls.newInstance(); //获取对象方法 Method method = cls.getMethod(methodName); //执行方法 method.invoke(obj); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)