通过反射加载配置文件的方式加载类
- 创建配置文件(以properties结尾)
className=Entity.Student
methodName=sleep
- 创建本次实验的实体类Person
public class Person {
private String name;
private String age;
public String a;
public String b;
protected String c;
protected String d;
public Person() {
}
public Person(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public Person setName(String name) {
this.name = name;
return this;
}
public String getAge() {
return age;
}
public Person setAge(String age) {
this.age = age;
return this;
}
public String getA() {
return a;
}
public Person setA(String a) {
this.a = a;
return this;
}
public String getB() {
return b;
}
public Person setB(String b) {
this.b = b;
return this;
}
public String getC() {
return c;
}
public Person setC(String c) {
this.c = c;
return this;
}
public String getD() {
return d;
}
public Person setD(String d) {
this.d = d;
return this;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
", a='" + a + '\'' +
", b='" + b + '\'' +
", c='" + c + '\'' +
", d='" + d + '\'' +
'}';
}
public void eat(){
System.out.println("吃饭");
}
public void eat(String rou){
System.out.println("吃"+rou);
}
}
- 核心加载代码
public class ReflectCase {
public static void main(String[] args)throws Exception {
Properties properties = new Properties();
ClassLoader classLoader = ReflectCase.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("pro.properties");
properties.load(is);
String className=properties.getProperty("className");
String methodName=properties.getProperty("methodName");
Class<?> cls= Class.forName(className);
Object obj = cls.newInstance();
Method method = cls.getMethod(methodName);
method.invoke(obj);
}