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

问题描述 投票:2回答:1

我想创建这样一个接口

public interface MyInterface<T extends OtherInterface<K>>{
    K doSomething(T o);
}

但是编译器将无法识别它。周围的其他方法是:

public interface MyInterface<T extends OtherInterface<K>,K>{
    K doSomething(T o);
}

我的问题是,虽然第二代码的工作,有没有像第一代码的方式,所以我没有把两种宣布的界面?

java
1个回答
0
投票

如果你有两个类型参数的通用接口,那么你需要声明他们两人在课堂上签名。

另外,如果申报K作为通配符?,就回到T,你仍然能够输出T转换为正确的接口。例如:

interface Foo<T> { }

interface Bar<T extends Foo<?>>{
    T doSomething(T o);
}

class IntegerFoo implements Foo<Integer> {}
...

public static void main(String[] args) {
    IntegerFoo integerFoo = new IntegerFoo();

    Bar<IntegerFoo> bar = t -> t;

    Foo<Integer> result = bar.doSomething(integerFoo);
}
© www.soinside.com 2019 - 2024. All rights reserved.