2012-12-26 94 views
2

可能重複:
Is it possible in Java to access private fields via reflection可以從課外訪問java私有數據成員嗎?

有沒有什麼辦法讓我們可以調用類的私有數據成員在Java中,可以在類的外部訪問。 我想這是一個棘手的問題銀行。 儘管我的Java體驗,我認爲這是可能的,但我不知道該怎麼做。

+4

參見[這](http://stackoverflow.com/q/1555658/1787809)或[是](http://stackoverflow.com/q/1771744/1787809) –

回答

6

按照Java語言規範,第三版:

6.6.8 Example: private Fields, Methods, and Constructors 

A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses. 

您可以使用reflection在java中訪問私有字段。理想情況下,你應該使用公共設置器和getter方法來訪問課堂以外的數據(如其他人發佈的那樣)

+0

安全性如何呢? Class概念的主要動機是直接限制訪問領域。如果有辦法訪問私有字段/方法,那麼在Java中如何確保安全性? – doga

0

定義一個公開的get方法來獲得你的班級的私人領域。

0

不,你不能通過任何方式訪問java中的私有變量。

您可以提供公共的getter和setter方法來訪問或更改私有成員變量的值。

+0

我知道這親愛的,但那不是我questioning.so請正確地讀問題 – Aarun

0
  1. 沒有私有成員不能在類
  2. 您可以使用getter和setter方法用於此目的
+0

我知道這親愛的私人不用在課堂上,但我需要一個代碼,使它成爲可能。 'class Other {private String str; public void setStr(String value) str = value; } } class Test { public static void main(String [] args) //只是爲了方便一次性測試。不要 //通常這樣做! 拋出異常 { 其他t = new Other(); t.setStr(「hi」); Field field = Other.class.getDeclaredField(「str」); field.setAccessible(true); Object value = field.get(t); System.out.println(value); } }' – Aarun

+1

我知道這個親愛的,但那不是我questioning.so請正確地讀問題 – Aarun

+0

@ArunKumarThakur是親愛的。您即將發佈的Java 8?抱歉回答你的問題已經是-3票了。 –

6

1)可以與反射做到這一點,如果安全管理器允許

class B { 
    private int x = 2; 
} 

public class A { 

    public static void main(String[] args) throws Exception { 
     Field f = B.class.getDeclaredField("x"); 
     f.setAccessible(true); 
     f.get(new B()); 
    } 
} 

2)在內部類

的情況下
class A { 
    private int a = 1; 

    class B { 
     private int b = 2; 

     private void xxx() { 
      int i = new A().a; 
     }; 
    } 

    private void aaa() { 
     int i = new B().b; 
    } 
+0

thanx親愛的,多數民衆贊成在我爲... ..... – Aarun

+0

爲此目的,這兩個類應該在一個包? –

+0

@Android Killer反射無所謂,f.setAccessible(true)打破安全。 –

0

可以使用公共方法返回做/設置私人字段值。

public Class A{ 

    private String myData; 

    public String getMyData(){ 
     return myData; 
    } 

    public void setMyData(String data){ 
     this.myData=data; 
    } 
}