《Effective Java》单例模式创建多对象

package com.base.test;

/**
 * 通过 AccessibleObject.setAccessible(...)来实例化构造器私有类
 * 
 * @author ZHEN.L
 * @DATE 2016.04.22
 * 
 */
public class StudentDto {

	private static StudentDto s = new StudentDto();

	private StudentDto() {
	}

	public static StudentDto getInstance() {
		return s;
	}

}
<pre name="code" class="java">import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import com.base.test.StudentDto;

public class Test {

	public static void main(String[] args) {
		StudentDto a1 = StudentDto.getInstance();
		// Field[] fields = a1.getClass().getDeclaredFields();
		Constructor[] cons = a1.getClass().getConstructors();
		AccessibleObject.setAccessible(cons, true);
		System.out.println(cons.length);
		try {
			System.out.println(cons[0].toString() + " = " + cons[0].newInstance());
			System.out.println(cons[0].toString() + " = " + cons[0].newInstance());
			System.out.println(cons[0].toString() + " = " + cons[0].newInstance());

			// System.out.println(fields[0].toString() + "=" +
			// fields[0].get(a1));
			// fields[0].set(a1, "123");
			// System.out.print(fields[0].toString() + "=" + fields[0].get(a1));

		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}


 

你可能感兴趣的:(《Effective Java》单例模式创建多对象)