JAVA--用反射读取配置文件
//配置文件 test.properties className = Reflection.Student methodName = show test.txt className = Reflection.Student methodName = show
package Reflection; public class Student { public void show(){ System.out.println("hhh"); } public void show(String s){ System.out.println(s); } }
package Reflection; import java.lang.reflect.Method; import java.util.Properties; public class ReflectFile { //txt、properties public static void main(String[] args) throws Exception{ //获取配置文件对象 Properties pro=new Properties(); //方式1 // //获取输入流 // FileReader in = new FileReader("test.txt"); // //将流加载到配置文件对象中 // pro.load(in); //方式二 pro.load(ReflectFile.class.getClassLoader().getResourceAsStream("test.properties")); //通过反射获取Class对象 String forName=pro.getProperty("className"); Class stuClass=Class.forName(forName); //获取方法 String methodName=pro.getProperty("methodName"); Method m=stuClass.getMethod(methodName); //调用方法 m.invoke(stuClass.getConstructor().newInstance(),null); //获取方法 methodName=pro.getProperty("methodName"); m=stuClass.getMethod(methodName,String.class); //调用方法 m.invoke(stuClass.getConstructor().newInstance(),"null"); } }
下一篇:
用java实现双色球彩票