//1.读取配置文件的信息 Properties prop = new Properties(); FileInputStream fis = new FileInputStream("D:\\java\\xuexi\\test\\prop.properties"); prop.load(fis); fis.close(); //2.获得全类名和方法名 String classname= (String) prop.get("classname"); String methodname= (String) prop.get("method"); System.out.println(classname);//test8.Teacher System.out.println(methodname);//teach //3.利用反射创建对象运行方法 Class clazz = Class.forName(classname); //获得构造方法 Constructor con = clazz.getDeclaredConstructor(); System.out.println(con);//public test8.Teacher() //根据指定的构造方法创建对象 Object o = con.newInstance(); System.out.println(o);//Teacher{name = null, salary = 0.0} //获得成员方法 Method method = clazz.getDeclaredMethod(methodname); method.setAccessible(true); method.invoke(o);
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("老师在教书!"); } /** * 获取 * @return name */ public String getName() { return name; } /** * 设置 * @param name */ public void setName(String name) { this.name = name; } /** * 获取 * @return salary */ public double getSalary() { return salary; } /** * 设置 * @param salary */ public void setSalary(double salary) { this.salary = salary; } public String toString() { return "Teacher{name = " + name + ", salary = " + salary + "}"; } }
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("学生在学习!"); } /** * 获取 * @return name */ public String getName() { return name; } /** * 设置 * @param name */ public void setName(String name) { this.name = name; } /** * 获取 * @return age */ public int getAge() { return age; } /** * 设置 * @param age */ public void setAge(int age) { this.age = age; } public String toString() { return "Student{name = " + name + ", age = " + age + "}"; } }