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

标签 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>>

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

最佳答案

来自 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

关于java - 类型参数 T 不在其范围内;应该扩展 MyBaseClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50646585/

相关文章:

c# - .NET 运行时序列化

java错误两种方法对泛型有相同的删除

c# - 在 C# 的泛型方法中使用枚举

java - 接口(interface) Enum 的静态方法

c# - 如何在 Java 中声明一个全局静态类?

c# - 通过反射调用带有 params 参数的泛型方法

java - 实现Clonable接口(interface),但不必重写clone()方法

java - 在Java中将列表中的元素分组到不重复的子列表中

java - 在域对象生成器中进行 Spring 验证是个好主意吗?

java - 使用 MyBatis 3 插入对象列表