Person 类:
package Day32_Reflection.ReflectProperties;
/**
* @Author quzheng
* @Date 2019/10/7 23:46
* @Version 1.0
*/
public class Person {
public void eat(){
System.out.println("人在吃饭");
}
}
Student 类:
package Day32_Reflection.ReflectProperties;
/**
* @Author quzheng
* @Date 2019/10/7 23:46
* @Version 1.0
*/
public class Student {
public void study(){
System.out.println("学生在学习");
}
}
Worker 类:
package Day32_Reflection.ReflectProperties;
/**
* @Author quzheng
* @Date 2019/10/7 23:47
* @Version 1.0
*/
public class Worker {
public void work(){
System.out.println("上班族在工作");
}
}
反射类:
package Day32_Reflection.ReflectProperties;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
/**
* @Author quzheng
* @Date 2019/10/7 23:48
* @Version 1.0
*
* 既能调用 Person 方法 也能调用 Student方法 也能调用 Worker方法
* 通过 配置文件实现
* 将 允许的类名和方法名 以键值对 存储在文本中
* 1.准备配置文件
* 2.IO流读取配置文件 Reader
* 3.文件中键值对 存储到集合中 Properties
* 4.反射 获取指定类的class文件 class 文件获取指定方法,并运行
*/
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
// IO流读取配置文件
FileReader r = new FileReader("D:\\Java_30Days\\src\\Day32_Reflection\\ReflectProperties\\config.properties");
//创建集合对象
Properties p = new Properties();
// 调用集合方法 传递流对象
p.load(r);
r.close();
// 通过键 获取值
String className = p.getProperty("className");
String methodName = p.getProperty("methodName");
//反射获取指定类的 class 文件
Class c = Class.forName(className);
Method m = c.getMethod(methodName);
Object obj = c.newInstance();
m.invoke(obj);
}
}
配置文件的键值对:config.properties
className=Day32_Reflection.ReflectProperties.Student
methodName=study
网友评论