單例類:
1 package singleton; 2
3 public class SingletonTest { 4
5 // 私有構造方法
6 private SingletonTest(){ 7
8 System.out.println("無參數---構造----"); 9 } 10 // 私有構造方法
11 private SingletonTest(String a){ 12
13 System.out.println("有參數---構造----參數值:" + a); 14 } 15 //定義私有類型的變量
16 private static volatile SingletonTest instance; 17
18 //定義一個靜態共有方法
19 public static SingletonTest getInstance(){ 20
21 if(instance == null){ 22 synchronized(SingletonTest.class){ 23 if(instance == null){ 24 return new SingletonTest(); 25 } 26 } 27 } 28 return instance; 29 } 30 }
測試調用類:
1 package reflect; 2
3 import java.lang.reflect.Constructor; 4 import java.lang.reflect.Method; 5
6 import singleton.SingletonTest; 7
8 public class ReflectDemo { 9
10 public static void main(String[] args) throws Exception{ 11 Class clazz = SingletonTest.class; 12
13 /*以下調用無參的、私有構造函數*/
14 Constructor c0= clazz.getDeclaredConstructor(); 15 c0.setAccessible(true); 16 SingletonTest po=(SingletonTest)c0.newInstance(); 17 System.out.println("無參構造函數\t"+po); 18
19 /*以下調用帶參的、私有構造函數*/
20 Constructor c1=clazz.getDeclaredConstructor(new Class[]{String.class}); 21 c1.setAccessible(true); 22 SingletonTest p1=(SingletonTest)c1.newInstance(new Object[]{"我是參數值"}); 23 System.out.println("有參的構造函數\t"+p1); 24
25 } 26
27 }
結果:
1 無參數---構造----
2 無參構造函數 singleton.SingletonTest@11ff436 3 有參數---構造----參數值:我是參數值 4 有參的構造函數 singleton.SingletonTest@da3a1e
參考資料