java reflect templete

使用Hashtable 的子类—— Properties 完成。

import java.util.* ;
import java.io.* ;

interface Fruit{
public void grow() ;
public void eat() ;
}
class Apple implements Fruit{
public void grow(){
System.out.println("苹果在生长。。。") ;
}
public void eat(){
System.out.println("吃苹果。。。") ;
}
};
class Orange implements Fruit{
public void grow(){
System.out.println("橘子在生长。。。") ;
}
public void eat(){
System.out.println("吃橘子。。。") ;
}
};
class Banana implements Fruit{
public void grow(){
System.out.println("香蕉在生长。。。") ;
}
public void eat(){
System.out.println("吃香蕉。。。") ;
}
};
class Factory{



public static Fruit getFruit(String className){
Fruit f = null ;

try {
f = (Fruit)Class.forName(className).newInstance() ;

}catch(Exception e){}
return f ;

}
};











class PropertyOperate{
private Properties pro = null ;
public PropertyOperate(){
this.pro = new Properties() ;
this.load() ;
}
// 设置一个返回方法
public Properties getPro(){
return this.pro ;
}

// 从文件中读出属性,如果文件不存在,则创建一个默认的
private void save(){

pro.setProperty("a","Apple") ;
pro.setProperty("o","Orange") ;

// 保存在文件之中
try {

pro.storeToXML(new FileOutputStream(new File("f:\\fruit.xml")),"FRUIT FACTORY") ;
}catch(Exception e){}

}
private void load(){

File f = new File("f:\\fruit.xml") ;
if(f.exists()){

// 文件存在,则可以读取
try {

pro.loadFromXML(new FileInputStream(f)) ;
}catch(Exception e){}

}else{
// 进行创建
this.save() ;
}
}
};
class InputData{
private BufferedReader buf = null ;
public InputData(){
this.buf = new BufferedReader(new InputStreamReader(System.in)) ;
}
public String getString(){
String str = null ;
try {
str = this.buf.readLine() ;
}catch(Exception e){}
return str ;
}
};



public class Demo{
public static void main(String args[]){
Properties p = new PropertyOperate().getPro() ;
System.out.println(p) ;
System.out.print("请选择所需要的类型:") ;
String str = new InputData().getString() ;
// 进一步扩展,现在可以由用户自己输入,要使用的类型
Fruit f = Factory.getFruit(p.getProperty(str)) ;
f.grow() ;
}


};



最好在try catch 中的catch中异常信息,以便log查看.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值