單例類:
package singleton; public class SingletonTest { // 私有構造方法 private SingletonTest(){ System.out.println("無參數---構造----"); } // 私有構造方法 private SingletonTest(String a){ System.out.println("有參數---構造----參數值:" + a); } //定義私有類型的變量 private static volatile SingletonTest instance; //定義一個靜態共有方法 public static SingletonTest getInstance(){ if(instance == null){ synchronized(SingletonTest.class){ if(instance == null){ return new SingletonTest(); } } } return instance; } }
測試調用類:
package reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import singleton.SingletonTest; public class ReflectDemo { public static void main(String[] args) throws Exception{ Class clazz = SingletonTest.class; /*以下調用無參的、私有構造函數*/ Constructor c0= clazz.getDeclaredConstructor(); c0.setAccessible(true); SingletonTest po=(SingletonTest)c0.newInstance(); System.out.println("無參構造函數\t"+po); /*以下調用帶參的、私有構造函數*/ Constructor c1=clazz.getDeclaredConstructor(new Class[]{String.class}); c1.setAccessible(true); SingletonTest p1=(SingletonTest)c1.newInstance(new Object[]{"我是參數值"}); System.out.println("有參的構造函數\t"+p1); } }
輸出結果:
無參數---構造----
無參構造函數 singleton.SingletonTest@11ff436
有參數---構造----參數值:我是參數值
有參的構造函數 singleton.SingletonTest@da3a1e