package Reflects; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Properties; import java.util.stream.Stream; public class ReflectDemo2 { public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { System.out.println("=====练习:通过配置文件进行类操作====="); Properties p = new Properties(); // p.setProperty("className","Reflects.Student"); // p.setProperty("classMethod","study"); p.setProperty("className","Reflects.Teacher"); p.setProperty("classMethod","say"); FileWriter fileWriter = new FileWriter("./config.txt"); p.store(fileWriter,null); fileWriter.close(); //读区 FileReader fr = new FileReader("./config.txt"); p.load(fr); fr.close(); String className = p.getProperty("className"); String classMethod = p.getProperty("classMethod"); Class<?> aClass = Class.forName(className); //获取类文件对象 Constructor<?> constructor = aClass.getConstructor();//构造方法 Object o = constructor.newInstance();//创建对象 Method method = aClass.getMethod(classMethod); method.invoke(o); } }