• 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 + "]";
    	}
    }
    

      

  • 相关阅读:
    java下载url图片链接
    mysql 设计索引的原则
    169. 多数元素
    263. 丑数
    markdown 语法笔记
    70.爬楼梯
    540. 有序数组中的单一元素
    88. 合并两个有序数组
    面试题57
    152. 乘积最大子序列
  • 原文地址:https://www.cnblogs.com/1020182600HENG/p/7360760.html
Copyright © 2020-2023  润新知