2011-09-26 51 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(); 

}