反射如何破坏单例模式

一个单例类:

 
 
?
1
2
3
4
5
6
7
8
9
public class Singleton {
     private static Singleton instance = new Singleton();  
 
     private Singleton() {}
 
     public static Singleton getInstance() {
         return instance;
     }
}
 

通过反射破坏单例模式:

 
 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Test {
     public static void main(String[] args) throws Exception{
         Singleton s1 = Singleton.getInstance();
 
         Constructor<Singleton> constructor = Singleton. class .getDeclaredConstructor();
         constructor.setAccessible( true );
         Singleton s2 = constructor.newInstance();
 
         System.out.println(s1.hashCode());
         System.out.println(s2.hashCode());
 
     }
}
 
 

  

输出结果:
671631440

935563443

结果表明s1和s2是两个不同的实例了。

通过反射获得单例类的构造函数,由于该构造函数是private的,通过setAccessible(true)指示反射的对象在使用时应该取消 Java 语言访问检查,使得私有的构造函数能够被访问,这样使得单例模式失效。

 

如果要抵御这种攻击,要防止构造函数被成功调用两次。需要在构造函数中对实例化次数进行统计,大于一次就抛出异常。

 
 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Singleton {
     private static int count = 0 ;
 
     private static Singleton instance = null ;
 
     private Singleton(){
         synchronized (Singleton. class ) {
             if (count > 0 ){
                 throw new RuntimeException( "创建了两个实例" );
             }
             count++;
         }
 
     }
 
     public static Singleton getInstance() {
         if (instance == null ) {
             instance = new Singleton();
         }
         return instance;
     }
 
     public static void main(String[] args) throws Exception {
 
         Constructor<Singleton> constructor = Singleton. class .getDeclaredConstructor();
         constructor.setAccessible( true );
         Singleton s1 = constructor.newInstance();
         Singleton s2 = constructor.newInstance();
     }
 
}
 执行结果:
?
1
2
3
4
5
6
7
8
9
Exception in thread "main" java.lang.reflect.InvocationTargetException
     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
     at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
     at java.lang.reflect.Constructor.newInstance(Unknown Source)
     at com.yzz.reflect.Singleton.main(Singleton.java: 33 )
Caused by: java.lang.RuntimeException: 创建了两个实例
     at com.yzz.reflect.Singleton.<init>(Singleton.java: 14 )
     ... 5 more
 
 
在通过反射创建第二个实例时抛出异常,防止实例化多个对象。构造函数中的synchronized是为了防止多线程情况下实例化多个对象。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值