zoukankan      html  css  js  c++  java
  • 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 + "]";
    	}
    }
    

      

  • 相关阅读:
    Ubuntu 拦截并监听 power button 的关机消息
    Android 电池管理系统架构总结 Android power and battery management architecture summaries
    Linux 内核代码风格
    Linux 内核工作队列之work_struct 学习总结
    微信小程序 登录流程规范解读
    微信小程序监听input输入并取值
    koala 编译scss不支持中文(包括中文注释),解决方案如下
    阻止冒泡和阻止默认事件的兼容写法
    使用setTimeout实现setInterval
    css实现视差滚动效果
  • 原文地址:https://www.cnblogs.com/1020182600HENG/p/7360760.html
Copyright © 2011-2022 走看看