有没有办法让一个泛型类型的接口在 Java 中用另一个泛型类型扩展另一个接口?

我想创建一个这样的界面


public interface MyInterface<T extends OtherInterface<K>>{

    K doSomething(T o);

}

但编译器不会识别它。另一种方法是:


public interface MyInterface<T extends OtherInterface<K>,K>{

    K doSomething(T o);

}

我的问题是,虽然第二个代码有效,但有没有像第一个代码那样的方法,所以我不必放两种类型来宣布接口?


qq_花开花谢_0
浏览 83回答 1
1回答

胡说叔叔

如果您有一个带有两个类型参数的通用接口,那么您需要在类签名中声明它们。或者,如果声明K为通配符?并仅返回T,您仍然可以将输出T转换为正确的接口。例如:interface Foo<T> { }interface Bar<T extends Foo<?>>{&nbsp; &nbsp; T doSomething(T o);}class IntegerFoo implements Foo<Integer> {}...public static void main(String[] args) {&nbsp; &nbsp; IntegerFoo integerFoo = new IntegerFoo();&nbsp; &nbsp; Bar<IntegerFoo> bar = t -> t;&nbsp; &nbsp; Foo<Integer> result = bar.doSomething(integerFoo);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java