2011-09-26 49 views
1
interface I1 { ... } 
interface I2 { ... } 
interface I3 { ... } 
interface I4 { ... } 

interface MyFactory { 
    Object<? extends I1 & I2 & I3> createI1I2I3(); // doesn't work 
    Object<? extends I2 & I3 & I4> createI2I3I4(); // doesn't work 
} 

有一招,辦呢?我想這樣的事情在Java中的接口中使用固定類型約束?

interface I1I2I3 extends I1, I2, I3 { ... } 

I1I2I3!= <? extends I1 & I2 & I3>。有一個原因,我不能使用這種方法 - I1I2I3是外國的代碼。

更新

對於那些誰好奇,爲什麼會有人需要這樣一個奇怪的事情:

interface Clickable {} 
interface Moveable {} 
interface ThatHasText {} 

interface Factory { 
    Object<? extends Clickable> createButton(); // just a button with no text on it 
    Object<? extends Clickable & ThatHasText> createButtonWithText(); 
    Object<? extends Moveable & ThatHasText> createAnnoyingBanner(); 
} 
+2

我學習了這樣的構造的用例... –

+0

看到我的更新;-) – agibalov

回答

2

Object不接受類型參數可以使用下面的結構來代替:

interface I1 { } 
interface I2 { } 
interface I3 { } 
interface I4 { } 

interface MyFactory { 
    public <T extends I1 & I2 & I3> T createI1I2I3(); 
    public <T extends I2 & I3 & I4> T createI2I3I4(); 
} 
+0

絕對是的!謝謝! – agibalov

2

你的返回類型應該是參數化的,所以你可以做

interface MyFactory { 

    <T extends I1 & I2 & I3> T createI1I2I3(); 

}