类加载机制和反射一直是java中的一个核心模块,下面我通过自己写的案例来展示通过反射来创建类对象的一个工厂。
案例代码如下:
package com.xiaomo.reflex;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class ObjectPoolFactory {
//定义一个对象池,前面是对象名,后面是实际对象
private Map<String,Object> objectPool = new HashMap<>();
//定义一个创建对象的方法
//该方法只要传入一个字符串类名,程序可以根据该类名生成Java对象
private Object createObject(String clazzName) throws IllegalAccessException,ClassNotFoundException, InstantiationException, IllegalAccessException{
//根据字符串来获取对象的Class对象
Class<?> clazz = Class.forName(clazzName);
//使用clazz对应类的默认构造器创建实例
return clazz.newInstance();
}
public void initPool(String fileName) throws IllegalAccessException, ClassNotFoundException, InstantiationException{
try(
FileInputStream fis = new FileInputStream(fileName);
){
Properties props = new Properties();
props.load(fis);
for(String name:props.stringPropertyNames()){
//每取出一对key-value对,就根据value创建一个对象
//调用createObject()创建对象,并将对象添加到对象池中
objectPool.put(name, createObject(props.getProperty(name)));
}
}catch (IOException e) {
e.printStackTrace();
System.out.println("读取"+fileName+"异常");
}
}
public Object getObject(String name){
//从objectPool中取出指定那么对应的对象
return objectPool.get(name);
}
public static void main(String[] args) throws Exception {
ObjectPoolFactory pf = new ObjectPoolFactory();
pf.initPool("e:/reflex.txt");
System.out.println(pf.getObject("date"));
System.out.println(pf.getObject("jFrame"));
}
}
运行结果:
Fri Oct 11 11:51:28 CST 2013
javax.swing.JFrame[frame0,0,0,0x0,invalid,hidden,layout=java.awt.BorderLayout,title=,resizable,normal,defaultCloseOperation=HIDE_ON_CLOSE,rootPane=javax.swing.JRootPane[,0,0,0x0,invalid,layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
出处:http://blog.csdn.net/cl05300629/article/details/12614245 作者:伫望碧落