2010-10-29 188 views
7

簡而言之,我試圖去做「classObject.getDeclaredClasses()」的反例。從內部類對象中獲取外部類對象

我有一種方法接收類型爲Class<? extends Object>的對象。我想弄清楚它是否是內部類,如果是,我想訪問周圍類的對象實例。

是否有一個聰明的API,或者我不得不做一些字符串操作和解析?

回答

20

你正在尋找的Class.getDeclaringClass()方法:

公共類getDeclaringClass()

如果此Class對象所表示的類或接口是 另一個類的成員,返回表示類對象它在其中聲明的類別 。如果此類或接口不是任何其他類的 成員,則此方法返回null。如果這個Class對象表示一個數組類,或者一個原始類型,或者void,那麼這個方法返回null。

返回:聲明類該類

+0

唉的一個實例被實例化,我感到笨。當然,我正在尋找這個。謝謝! – 2010-10-29 11:18:48

1

引用外部類實例從內類代碼

如果內部類代碼需要,它連接到外部類實例的引用,使用外部類,一個點的名稱,這

* remember that if there is no name conflict, there is no need for any special syntax 
* for code in MyInner to obtain a reference to its MyOuter: 

    MyOuter.this 

靜態內部類

內部類可以被標記爲靜態

靜態內部類我沒有外部類

* static members of the outer class are visible to the inner class, no matter what their access level 
* non-static members of the outer class are not available, since there is not instance of the outer class to retrieve them from 
相關問題