forName读取类配置文件
// 配置文件
com.demo.Apple
// 执行类
public class Demo_Reflect {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("config.properties"));
Class clazz = Class.forName(br.readLine());// 读取配置文件中的包名称和类名称
Fruit f = (Fruit) clazz.newInstance();// 创建实例(苹果) 父类引用子类对象
Juicer j = new Juicer();
j.run(f);
}
}
interface Fruit {
public void squeeze();// 榨汁
}
class Apple implements Fruit {
@Override
public void squeeze() {
System.out.println("榨出一杯苹果汁");
}
}
class Orange implements Fruit {
@Override
public void squeeze() {
System.out.println("榨出一杯橘汁");
}
}
class Juicer {
public void run(Fruit f) {
f.squeeze();// 执行榨汁
}
}