People:
package com.javaWeb02; public class Person { public void eat(){ System.out.println("eat..."); } }
Student:
package com.javaWeb02; public class Student { public void study(){ System.out.println("study..."); } }
pro.properties的位置:{
className=com.javaWeb02.Student methodName=study
}
reflectTest:模拟写框架
package com.javaWeb02; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.Properties; public class ReflectTest { /* 写一个框架在不改变该类的任何情况下,创建任意类的对象,并执行其中的方法 */ public static void main(String[] args) throws Exception { //创建Properties对象 Properties properties=new Properties(); //获取class目录下的配置文件(使用类加载器) ClassLoader classLoader = ReflectTest.class.getClassLoader(); //加载配置文件 InputStream resourceAsStream = classLoader.getResourceAsStream("pro.properties"); properties.load(resourceAsStream); //获取配置文件中定义的数据 String className=properties.getProperty("className"); String methodName=properties.getProperty("methodName"); //加载该类进内存 Class cls = Class.forName(className); //创建对象 Object o = cls.newInstance(); //获取方法 Method method = cls.getMethod(methodName); //执行方法 method.invoke(o); } }