2012-03-30 23 views
-1

我想將一個類實例傳遞給另一個類的方法,並確保它實現了所需的接口。該代碼是這樣的如何將實例傳遞給必須實現接口的類,然後在java中使用它?

public interface MyInterface{ 
    someMethod(); 
} 

public class A implements MyInterface{ 
    B bInst; 
    public someMethod(){ 
     //stuff 
    } 

    public bar(){ 
     bInst = new B(this); // [4] 
    } 
} 

public class B{ 

    private MyInterface x;  //[1] 

    // here i don't want to use 
    void B(MyInterface y){  // [2] 
     this.x=y;   // [3] 
    } 

    private void foo(){ 
     x.someMethod(); 
    } 

} 

我試着在[1] [2] subsituting 「MyInterface的」 「<類?擴展IBtBytesReciever>」,但是編譯器給我的錯誤,或者在[2]或[3 ]。

實現我的想法的最佳方式是什麼?

注:我不想因爲B類不需要知道類的確切名稱,直接使用A類和它必須是可重複使用的不同類別

編輯:錯誤是[ 4]

constructor B(class A) not defined 
+1

你不喜歡'void B(MyInterface y)'?它似乎完全符合你的意思.. – 2012-03-30 19:29:46

+1

你得到的錯誤信息是什麼? – ControlAltDel 2012-03-30 19:30:39

+0

編譯器錯誤是什麼? – Kashyap 2012-03-30 19:31:12

回答

4

這不是很清楚你的意思是「這裏我不想用」,但基本上你的構造函數寫得不對。它應該只是:

// Or make it non-public if you want, of course. 
public B(MyInterface y) { 
    this.x = y; 
} 

這將做正是你想要的:防止任何不被傳遞到構造函數實現的接口。爲什麼你想要使它通用,或者傳遞一個類引用呢?

可以將其更改爲:

public B(Class<? extends MyInterface> clazz) { 
    // TODO: catch or declare all the various exceptions this could throw 
    this.x = clazz.newInstance(); 
} 

...但感覺很彆扭這樣做。

編輯:只是要說清楚,這絕對是罰款致電new B(this)。簡短但完整的例子,使用您的代碼作爲起動器:

interface MyInterface{ 
    void someMethod(); 
} 

class A implements MyInterface{ 
    B bInst; 
    public void someMethod(){ 
    } 

    public void bar() { 
     bInst = new B(this); 
    } 
} 

class B { 
    private MyInterface x; 

    B(MyInterface y) { 
     this.x=y; 
    } 

    private void foo(){ 
     x.someMethod(); 
    }  
} 

這將工作絕對好。

+0

我的想法是通過已初始化的實例 – Zorb 2012-03-30 19:41:04

+0

@Zorb:所以這很好 - 你可以將相同的引用傳遞給'B'構造函數多次...它真的不清楚什麼第一種方法*沒有*達到你想要的... – 2012-03-30 19:41:50

+0

問題是在第一種方式我不能稱之爲「bInst = new B(this);」因爲構造函數是用於MyInterface而不是我從 – Zorb 2012-03-30 19:50:41

3

我試着在[1] [2] 「<類?擴展IBtBytesReciever>」

這是你的錯誤subsituting 「MyInterface的」。 Class<? extends IBtBytesReciever>描述了類對象的類型,您可能需要進行反思,但在此不需要。

類對象和類實例之間的差異就像關於大象和特定大象的維基百科條目之間的差異。維基百科條目通常包含關於大象的元數據,但是如果您想對大象進行操作,在大多數情況下您需要一頭真實的大象。

在這樣的方法:

void foo(MyInterface instance) 
{ 

} 

可以調用foo()與實現MyInterface的類的任何有效的實例。

相關問題