标签:ref stream package exception 配置 abs trace tac null
package designMode;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
interface Fruit{
public abstract void eat();
}
class Apple implements Fruit{
public void eat(){
System.out.println("Apple");
}
}
class Orange implements Fruit{
public void eat(){
System.out.println("Orange");
}
}
class Factory{
public static Fruit getInstance(String className){
Fruit f=null;
try{
f=(Fruit)Class.forName(className).newInstance();
}catch (Exception e) {
e.printStackTrace();
}
return f;
}
}
/*
* *方法2 通过配置文件
*/
class init{
public static Properties getPro() throws FileNotFoundException, IOException{
Properties pro=new Properties();
File f=new File("resources/fruit.properties");
if(f.exists()){
pro.load(new FileInputStream(f));
}
else{
pro.setProperty("apple", "designMode.Apple");
pro.setProperty("orange", "designMode.Orange");
pro.store(new FileOutputStream(f), "FRUIT CLASS");
}
return pro;
}
}
public class ReflectFactoryIOC {
public static void main(String[] a) throws FileNotFoundException, IOException{
/*
* *方法1
*/
/* Fruit f=Factory.getInstance("designMode.Apple");
if(f!=null){
f.eat();
}
*/
/*
* *方法2
*/
Properties pro=init.getPro();
Fruit ff=Factory.getInstance(pro.getProperty("orange"));
System.out.println(pro.toString());
if(ff!=null){
ff.eat();
}
}
}
/*fruit.properties*/
apple=designMode.Apple
orange=designMode.Orange
标签:ref stream package exception 配置 abs trace tac null
原文地址:https://www.cnblogs.com/Jmublog/p/12207307.html