类型参数T不在其范围内;应该扩展MyBaseClass

时间:2018-06-01 15:19:31

标签: java generics interface

我正在处理一些遗留代码,尝试重构和提取公共代码。我最终得到了以下层次结构。

public interface MyInterface<T extends MyBaseClass> {...}
public class MyBaseClass {...}
public class MyClass extends MyBaseClass implements MyOtherInterface<MyClass> {...}

public interface MyOtherInterface<T extends MyOtherInterface<T>> {
    void func(MyInterface<T> context);  // Complains that T should extend MyBaseClass
}

总之,我想指定传递给MyOtherInterface的参数T应该是一个扩展MyBaseClass并实现MyOtherInterface的类。像这样:

public interface MyOtherInterface<T extends MyOtherInterface<T extends MyBaseClass>>

我该怎么做?我想尽可能少地改变。我不确定以上是否可行,我可能不得不实际上翻转层次结构。

1 个答案:

答案 0 :(得分:1)

来自Oracle的Java教程:

Multiple Bounds

The preceding example illustrates the use of a type parameter with a single bound, but a type parameter can have multiple bounds:

<T extends B1 & B2 & B3> A type variable with multiple bounds is a subtype of all the types listed in the bound. If one of the bounds is a class, it must be specified first. For example:

Class A { /* ... */ } interface B { /* ... */ } interface C { /* ...
*/ }

class D <T extends A & B & C> { /* ... */ } If bound A is not specified first, you get a compile-time error:

class D <T extends B & A & C> { /* ... */ }  // compile-time error

来源:https://docs.oracle.com/javase/tutorial/java/generics/bounded.html