Java 反射 调用私有构造方法

时间:2023-02-16 22:40:24

  单例类:

 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

 

  参考资料

  Java反射机制调用private类型的构造方法