获取一个类里面所有的信息,获取到了之后,再执行其他的业务逻辑
结合配置文件,动态的创建对象并调用方法
练习1:
public class MyTest {public static void main(String[] args) throws IllegalAccessException, IOException {Student s = new Student("小A", 23, '女', 167.5, "睡觉");Teacher t = new Teacher("播妞", 10000);//调用方法upload(t);}private static void upload(Object obj) throws IllegalAccessException, IOException {//1创建字节码文件Class<?> clazz = obj.getClass();//2.创建io流BufferedWriter bw = new BufferedWriter(new FileWriter("..\\reflect\\a.txt"));//获取所有成员变量Field[] fields = clazz.getDeclaredFields();for (Field field : fields) {//暴力反射:因为成员变量有可能是私有化field.setAccessible(true);//获取变量名String name = field.getName();//获取变量在对象中记录的值Object value = field.get(obj);//写入文件bw.write(name + "=" + value);bw.newLine();}bw.close();}
}
练习二:
//Student
public class Student {private String name;private int age;public Student() {}public Student(String name, int age) {this.name = name;this.age = age;}public void study(){System.out.println("学生在学习!");}//set、get、toString
}
//Teacher
public class Teacher {private String name;private double salary;public Teacher() {}public Teacher(String name, double salary) {this.name = name;this.salary = salary;}public void teach(){System.out.println("老师在教书!");}// set、get、toString
}//main
public class Test {public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {//1.获取properties文件内的数据Properties prop = new Properties();FileInputStream fis=new FileInputStream("..\\reflect\\Info.properties");prop.load(fis);fis.close();System.out.println(prop);//{method=study, className=reflectDemo.Student}//根据键获取值String className = (String) prop.get("className");String methodName = (String)prop.get("method");//根据全类名获取class文件对象Class<?> clazz = Class.forName(className);//反射获取构造方法,创建一个对象oConstructor<?> constructor = clazz.getDeclaredConstructor();Object o = constructor.newInstance();//反射获取方法,参数是方法名Method method = clazz.getDeclaredMethod(methodName);//因为不知道方法是不是私有化,所以暴力反射method.setAccessible(true);//传入对象运行当前方法method.invoke(o);//学生在学习!}
}
准备一个info.properties文件,以键值对的形式存储
以后若要运行其他类里面的方法,在文件内修改数据即可
将文件修改为如下,再次运行
总结: