zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    多表关联查询(ORACLE版)
    开发中可能会用到的几个 jQuery 小提示和技巧 (转)
    让jquery easyui datagrid列支持绑定嵌套对象
    java图片处理工具类
    如何为Myeclipse手工添加dtd支持
    二进制与运算
    彻底卸载MYSQL,windows版
    Win7系统安装MySQL5.5.21图解教程
    Rust 资源整理
    【译】我的阅读习惯
  • 原文地址:https://www.cnblogs.com/zhihaospace/p/12326702.html
Copyright © 2011-2022 走看看