18.4.1创建对象

package d18_4_1;
/**
 * 创建对象1
 */
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> map = new HashMap<String, Object>();

	// 创建对象
	private Object createObject(String className)
			throws ClassNotFoundException, InstantiationException,
			IllegalAccessException {
		Class<?> claxx = Class.forName(className);
		return claxx.newInstance();
	}

	// 初始化对象池
	public void initPool(String fileName) throws IOException {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(fileName);
			Properties p = new Properties();
			p.load(fis);
			for (String name : p.stringPropertyNames()) {
				map.put(name, p.getProperty(name));
			}
		} catch (Exception e) {
			System.out.println("读取" + fileName + "异常");
		} finally {
			if (fis != null) {
				fis.close();
			}
		}
	}

	// 从对象池中取出指定name对应的对象
	public Object getObject(String name) {
		return map.get(name);
	}

	public static void main(String[] args) throws IOException {
		 ObjectPoolFactory pool=new ObjectPoolFactory();
		 pool.initPool("obj.text");
		 pool.getObject("a");
	}

}

  

 

package d18_4_1;
/**
 * 创建对象2
 */
import java.lang.reflect.Constructor;

public class CreateObject2 {

	public static void main(String[] args) throws Exception {
		Class c = Test2.class;
		Constructor con = c.getDeclaredConstructor(String.class);
		Object newInstance = con.newInstance("zhangsan");
		System.out.println(newInstance);
	}

}

class Test2 {
	private String name;
	private int age;
	String sex;

	private Test2() {

	}

	protected Test2(String name) {
		super();
		this.name = name;
	}

	public Test2(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public Test2(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Test2 [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
}

  

posted @ 2017-08-14 23:05  奋斗的少年WH  阅读(117)  评论(0编辑  收藏  举报