2012-08-14 75 views
0

我正在Swing應用程序中工作。我如何使用反射動態獲取調用者實例的實例

public class Owner extends JPanel{ 
    Child child=null; 
    public Owner(){ 
    child=new Child(); 
    } 
} 

public class Child extends JPanel{ 
    public Child(){ 
    // Here I want the instance of Owner class. 
    // This child class is being created from many classes(almost 1000) like the Owner class. 
    } 
} 

我想要一些方法來獲得調用類實例的實例,也許使用反射。 這樣我可以將KeyListener關聯到每個實例。 這是必需的,否則我必須在所有1000個類中編寫相同的代碼。

我所有的課程都在延伸JPanel,一旦組件與組件關聯到父組件,我就可以從Parent屬性獲取父組件。但是在這裏我需要它在Child的構造函數中,即組件還沒有與Owner關聯。

+1

看來設計天翻地覆,給予延長面板及需要從構造函數中訪問父。 – 2012-08-14 12:15:51

+0

「如何將參數傳遞給構造函數」是你的問題嗎?或者「我如何在我的1000個課程之間重複使用代碼」? – gontard 2012-08-14 20:07:45

回答

1
public class Owner extends JPanel{ 
Child child=null; 
public Owner(){ 
child=new Child(this); 
} 
} 

public class Child extends JPanel{ 
    Object owner ; 
    public Child(Object owner){ 
     this.owner = owner ; 
     // Here I want the instance of Owner class. 
     // This child class is being created from many classes(almost 1000) like the  Owner class. 
    } 
} 
+0

我不想改變我的1000個課程。 – 2012-08-14 21:12:17

+0

我不想改變我的1000個類中的任何一個(所有的都是視圖文件)。我的意圖是獲取它正在實例化的主視圖實例(這些代碼已經存在),然後我將關聯一個鍵聽從這個孩子班的觀點。 – 2012-08-14 21:18:21

0

類似的東西可以幫助你:

public class Owner extends JPanel { 
    Child child; 

    public Owner() { 
     child = new Child(this); 
    } 
} 

public class Child extends JPanel { 
    Owner owner; 

    public Child(Owner owner) { 
     this.owner = owner; 
     // add key listeners here to owner 
     owner.addKeyListener(...) 
    } 
}