![](/img/trans.png)
[英]accessing the private memeber variable of super class in the child class through reflection
[英]Accessing and modifying private class members through the use of reflection in Java
以下程序正在訪問和修改在類SimpleKeyPair
聲明的名為privateKey
的私有字段。 讓我們來看看它。
package mod;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
final class SimpleKeyPair
{
private String privateKey = "Welcome SimpleKeyPair ";
}
final public class Main
{
public static void main(String[] args)
{
SimpleKeyPair keyPair = new SimpleKeyPair();
Class c = keyPair.getClass();
try
{
Field field = c.getDeclaredField("privateKey"); // gets the reflected object
field.setAccessible(true);
System.out.println("Value of privateKey: " + field.get(keyPair)); // displays “Welcome SimpleKeyPair"
field.set(keyPair, "Welcome PrivateMemberAccessTest"); // modifys the private member varaible
System.out.println("Value of privateKey: " + field.get(keyPair));
}
catch (IllegalArgumentException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
catch (NoSuchFieldException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
catch (SecurityException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
在上面的代碼中,私人領域的privateKey
在類中聲明SimpleKeyPair
被訪問,並通過下面的語句顯示在控制台上。
Field field = c.getDeclaredField("privateKey");
field.setAccessible(true);
System.out.println("Value of privateKey: " + field.get(keyPair));
並且正在修改該字段,並通過以下語句顯示該字段的新值。
field.set(keyPair, "Welcome PrivateMemberAccessTest");
System.out.println("Value of privateKey: " + field.get(keyPair));
該程序的實際輸出如下。
Value of privateKey: Welcome SimpleKeyPair
Value of privateKey: Welcome PrivateMemberAccessTest
意味着在Java中使用反射可以直接訪問私有資源。 如果是這樣,那么在Java中將成員聲明為私有本身並不安全,盡管將類成員聲明為私有的目的之一就是將它們隱藏在外界之外。 Java中反射的實際用途是什么?
您是正確的,反射可以允許訪問類的私有(以及打包和受保護的)作用域成員。 但是,如果您閱讀JavaDocs,則會發現所有用於獲取和調用這些訪問器的方法在執行請求的操作之前都執行SecurityManager檢查。 因此,在具有SecurityManger的環境中,操作將因拋出SecurityExceptions而失敗。
反射有什么用? 內省,進行動態調用/解決方案,工具等的能力。
您是說private
的實際用途是什么? 宣布意圖,並禁止隨意濫用私人成員。 h
通常,當您要使用元數據時,反射很有用; 一個例子是像休眠這樣的orm框架,它使用很多反射功能,等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.