pro.properties文件(该文件与ReflectTest01同处在同一个文件夹);
className = domain.Person
methodName = eat
代码如下:
package domain;public class Student {public void sleep(){System.out.println("sleep...");}
}
package domain;public class Person {private String name;private int age;public String a;protected String b;String c;private String d;public Person() {}public Person(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +", a='" + a + '\'' +", b='" + b + '\'' +", c='" + c + '\'' +", d='" + d + '\'' +'}';}public void eat(){System.out.println("eat...");}public void eat(String food){System.out.println("eat..."+food);}}
package domain01;import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Properties;public class ReflectTest {public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
// Person p = new Person();
// p.eat();// Student t = new Student();
// t.sleep();//1.加载配置文件//1.1创建Properties对象Properties pro = new Properties();//1.2加载配置文件,转换为一个集合//1.2.1获取class目录下的配置文件ClassLoader classLoader = ReflectTest.class.getClassLoader();InputStream is = classLoader.getResourceAsStream("pro.properties");pro.load(is);//2.获取配置文件中定义的数据String className = pro.getProperty("className");String methodName = pro.getProperty("methodName");//3.加载该类进内存Class c = Class.forName(className);//4.创建对象Constructor<?> con = c.getConstructor();Object obj = con.newInstance();//5.获取方法对象Method method = c.getMethod(methodName);//6.执行方法method.invoke(obj);}
}
测试结果: