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

s5s*_*s5s 5 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
}
Run Code Online (Sandbox Code Playgroud)

换句话说,我想指定传递给MyOtherInterface的参数T应该是一个扩展MyBaseClass并实现MyOtherInterface的类。像这样的东西:

public interface MyOtherInterface<T extends MyOtherInterface<T extends MyBaseClass>>
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?我正在尝试尽可能少地改变。我不确定上述情况是否可行,我可能必须实际翻转层次结构。

s5s*_*s5s 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
Run Code Online (Sandbox Code Playgroud)

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