自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

80%的Java程序員不知道反射強行調(diào)用私有構(gòu)造器這事兒

開發(fā) 開發(fā)工具
在我之前的一篇文章里曾提到一個觀點:“可能會有人使用反射強行調(diào)用我們的私有構(gòu)造器”,很多童鞋不明白Java反射機制怎么做到調(diào)用私有構(gòu)造器,今天我們來做一個實驗。

在我之前的一篇文章里曾提到一個觀點:“可能會有人使用反射強行調(diào)用我們的私有構(gòu)造器”,很多童鞋不明白Java反射機制怎么做到調(diào)用私有構(gòu)造器,今天我們來做一個實驗。

實驗代碼

  1. import java.lang.reflect.*; 
  2. public class ReflectTest {   
  3.      public static void main(String[] args) throws Exception {        
  4.         //get Constructor 
  5.         Class clazz = Class.forName("TestOne"); 
  6.         Constructor cons = clazz.getDeclaredConstructor(null);  
  7.          
  8.         //set accessible to access private constructor   
  9.         cons.setAccessible(true); //1  
  10.         cons.newInstance(null);  
  11.         cons.newInstance(null);  
  12.      } 
  13. class TestOne { 
  14.     private TestOne() {   
  15.         System.out.println("init TestOne=="+this.hashCode());   
  16.     }   

實驗結(jié)果

注釋1處的代碼cons.setAccessible(true),執(zhí)行main函數(shù),出現(xiàn)異常Exception in thread "main" 

  1. java.lang.IllegalAccessException: Class ReflectTest can not access a member of class TestOne with modifiers "private" 

開啟1處的代碼cons.setAccessible(true),執(zhí)行main函數(shù),出現(xiàn)如下正常的初始化信息:

  1. init TestOne==12677476 
  2. init TestOne==33263331 

這說明私有構(gòu)造函數(shù)被多次成功調(diào)用,注意是私有構(gòu)造函數(shù)哦。

實驗總結(jié)

出現(xiàn)完全不同的兩種測試結(jié)果的原因是什么?我們來剖析一下cons.setAccessible(true)函數(shù),為什么設(shè)置為true時,可以通過反射調(diào)用私有構(gòu)造器呢?我們定位到cons.setAccessible(true)源代碼,可以看到下面的英文說明,右側(cè)已經(jīng)幫助大家翻譯了一下。

反射強行調(diào)用私有構(gòu)造器

也就是說,Java反射機制非常強大,可以根據(jù)需要繞過Java語言的訪問檢查。

原文是這樣說的:

Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks.

翻譯過來是這樣的:

  1. 將此對象的<tt>可訪問</ tt>標(biāo)志設(shè)置為指示的布爾值。 值<tt> true </ tt>表示反射對象應(yīng)該在使用時抑制Java語言訪問檢查。 值<tt> false </ tt>表示反射對象應(yīng)強制實施Java語言訪問檢查。 

【本文為51CTO專欄作者“朱國立”的原創(chuàng)稿件,轉(zhuǎn)載請通過作者微信公眾號“開發(fā)者圓桌”獲取聯(lián)系和授權(quán)】

 

戳這里,看該作者更多好文

責(zé)任編輯:趙寧寧 來源: 51CTO專欄
相關(guān)推薦

2012-01-06 15:03:54

2021-02-08 22:32:43

程序員 靜態(tài)網(wǎng)頁

2013-12-05 16:59:22

2018-05-08 15:30:46

程序員代碼框架

2018-11-01 13:57:25

AR醫(yī)療患者

2015-05-18 10:21:19

2022-08-08 11:13:35

API接口前端

2011-08-23 13:50:17

程序員

2014-03-12 09:23:06

DevOps團(tuán)隊合作

2014-03-24 09:16:55

2016-10-09 19:22:08

2018-09-20 17:05:01

前端程序員JavaScript

2019-07-12 15:28:41

緩存數(shù)據(jù)庫瀏覽器

2025-01-17 08:50:03

程序員支付寶國補

2021-03-01 19:13:45

YAML程序員數(shù)據(jù)

2013-11-21 13:35:19

程序員牛人

2018-11-25 10:08:44

阿里巴巴技術(shù)開源

2025-04-17 02:30:00

2021-01-12 12:33:20

Pandas技巧代碼

2025-04-01 00:26:46

參數(shù)技巧arglist
點贊
收藏

51CTO技術(shù)棧公眾號