码迷,mamicode.com
首页 > 编程语言 > 详细

java反射小例子

时间:2014-07-16 10:43:59      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:java反射小例子

package reflect;

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("eat Apple");
	}
	
}
class orange implements fruit{

	public void eat() {
		System.out.println("eat orange");
	}
	
}
class init{
	public static Properties getPro() throws FileNotFoundException, IOException{
		Properties pro = new Properties() ;
		File f = new File("fruit.properties") ;
		if(f.exists()){
			System.out.println("有配置文件!");
			//从配置文件中读取键值对
			pro.load(new FileInputStream(f)) ;
		}else{
			System.out.println("没有配置文件!");
			pro.setProperty("apple", "reflect.Apple") ;
			pro.setProperty("orange", "reflect.orange") ;
			pro.store(new FileOutputStream(f), "FRUIT CLASS") ;
		}
		return pro ;
	}
}
class Factory{
	public static fruit getInstance(String className){
		fruit f = null ;
		try {
			//通过反射得到fruit的实例对象
			f = (fruit)Class.forName(className).newInstance() ;
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return f ;
	}
}
public class Hello {
	public static void main(String[] args) {
		try {
			Properties pro = init.getPro() ;
			fruit f = Factory.getInstance(pro.getProperty("apple")) ;
			if(f != null){
				f.eat() ;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

bubuko.com,布布扣

结果为:

有配置文件!
eat Apple

java反射小例子,布布扣,bubuko.com

java反射小例子

标签:java反射小例子

原文地址:http://blog.csdn.net/benjamin_whx/article/details/37822285

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!