简体   繁体   English

在Java中使用接口内的固定类型约束?

[英]Using fixed type constraints inside an interface in Java?

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
}

Is there a trick to do it? 有这个诀窍吗? I was thinking about things like 我在考虑类似的事情

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

But I1I2I3 != <? extends I1 & I2 & I3> 但是I1I2I3 != <? extends I1 & I2 & I3> <? extends I1 & I2 & I3> . <? extends I1 & I2 & I3> There's a reason I just can't use this approach - I1 , I2 and I3 are foreign code. 有一个原因我不能使用这种方法 - I1I2I3是外国代码。

Update 更新

For those who curious why might someone need such a weird thing: 对于那些好奇为什么可能有人需要这样一个奇怪的事情的人:

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();
}

Object doesn't accept type parameter You can use the following construct instead: 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(); 
}

Your return type should be parameterized, so you can do 您的返回类型应该参数化,所以你可以这样做

interface MyFactory {

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM