反射实现工厂模式
程序员文章站
2022-03-09 21:52:20
...
package com.factory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.util.Properties;
public class TestDemo {
public static Properties getpro() throws Exception {
Properties p=new Properties();
File f=new File("animal.properties");
if(f.exists()) {
p.load(new FileInputStream(f));
}else {
p.setProperty("cat", "com.factory.Cat");
p.setProperty("dog", "com.factory.Dog");
p.store(new FileOutputStream(f),"文件说明");
}
return p;
}
public static void main(String[] args) throws Exception {
Properties p = TestDemo.getpro();
String pp = p.getProperty("cat");
Class c = Class.forName(pp);
//向上转型
Animal al = (Animal)c.newInstance();
Method m1=c.getMethod("shout", null);
m1.invoke(al, null);
}
}