2011-08-02 62 views
31

我試圖通過反射來獲取靜態私有屬性的值,但它失敗並顯示錯誤。是否可以通過反射調用私有屬性或方法

Class class = home.Student.class; 
Field field = studentClass.getDeclaredField("nstance"); 
Object obj = field.get(null); 

我得到的例外是:

java.lang.IllegalAccessException: Class com.test.ReflectionTest can not access a member of class home.Student with modifiers "private static". 

此外,還有一個私人我需要調用,用下面的代碼。

Method method = studentClass.getMethod("addMarks"); 
method.invoke(studentClass.newInstance(), 1); 

但問題是Student類是單例類,而構造函數是私有的,無法訪問。

回答

53

您可以設置訪問現場:

field.setAccessible(true); 
12

是的。你必須將它們用在AccesibleObject定義setAccessible(true)這是一個超類的都FieldMethod

隨着靜態字段訪問,你應該能夠做到:

Class class = home.Student.class; 
Field field = studentClass.getDeclaredField("nstance"); 
field.setAccessible(true); // suppress Java access checking 
Object obj = field.get(null); // as the field is a static field 
           // the instance parameter is ignored 
           // and may be null. 
field.setAccesible(false); // continue to use Java access checking 

與私營方法

Method method = studentClass.getMethod("addMarks"); 
method.setAccessible(true); // exactly the same as with the field 
method.invoke(studentClass.newInstance(), 1); 

並配有私人的構造函數:

Constructor constructor = studentClass.getDeclaredConstructor(param, types); 
constructor.setAccessible(true); 
constructor.newInstance(param, values); 
+0

的構造函數是私有的,我們仍然可以調用,通過使用'newInstance'方法??? –

1

是的,你可以「欺騙」這樣的:

Field somePrivateField = SomeClass.class.getDeclaredField("somePrivateFieldName"); 
    somePrivateField.setAccessible(true); // Subvert the declared "private" visibility 
    Object fieldValue = somePrivateField.get(someInstance); 
相關問題