Java通过反射破解单例模式和防止反射破解单例模式案例

一.通过反射破解和防止反射破解单例模式案例

 1 public class User {
 2 
 3     private String userName;
 4     private static User user;
 5 
 6     public String getUserName() {
 7         return userName;
 8     }
 9 
10     public void setUserName(String userName) {
11         this.userName = userName;
12     }
13 
14     private User(String userName) {
15 
16         // 2.这句话用于防止通过反射的方式调用该构造器创建对象
17         if (user != null) {
18             throw new RuntimeException("非法创建对象!");
19         }
20         this.userName = userName;
21     }
22 
23     public static User getInstance(String userName) {
24         if (user == null) {
25             user = new User(userName);
26         }
27         return user;
28     }
29 }
30 
31 class MyTest {
32 
33     public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
34         //1.通过反射破解单例模式
35         User user = User.getInstance("王");
36         System.out.println(user.getUserName());
37 
38         Class c1 = Class.forName("ustc.wzh.User");
39         Constructor<User> constructor = User.class.getDeclaredConstructor(String.class);
40         constructor.setAccessible(true);
41         User user1 = constructor.newInstance("张");
42 
43         System.out.println(user1.getUserName());
44         System.out.println(user.getUserName());
45     }
46 }

 

posted @ 2020-02-18 16:19  All_just_for_fun  阅读(953)  评论(0编辑  收藏  举报