Java 类型参数T不在其范围内;应该扩展MyBaseClass
我正在处理一些遗留代码,试图重构和提取公共代码。我最终得到了以下层次结构Java 类型参数T不在其范围内;应该扩展MyBaseClass,java,generics,interface,Java,Generics,Interface,我正在处理一些遗留代码,试图重构和提取公共代码。我最终得到了以下层次结构 public interface MyInterface<T extends MyBaseClass> {...} public class MyBaseClass {...} public class MyClass extends MyBaseClass implements MyOtherInterface<MyClass> {...} public interface MyOtherInt
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
}
公共接口MyInterface{…}
公共类MyBaseClass{…}
公共类MyClass扩展MyBaseClass实现MyOtherInterface{…}
公共接口MyOtherInterface{
void func(MyInterface context);//抱怨T应该扩展MyBaseClass
}
换句话说,我想指定传递给MyOtherInterface的参数T应该是一个扩展MyBaseClass并实现MyOtherInterface的类。大概是这样的:
public interface MyOtherInterface<T extends MyOtherInterface<T extends MyBaseClass>>
公共接口MyOtherInterface
我该怎么做?我正在尽可能少地改变。我不确定上述内容是否可行,我可能需要实际翻转层次结构。来自Oracle的Java教程:
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
}
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
多个边界
前面的示例演示了使用具有单个边界的类型参数,但类型参数可以具有多个边界:
具有多个边界的类型变量是边界中列出的所有类型的子类型。如果其中一个边界是类,则必须首先指定它。例如:
类A{/*…*/}接口B{/*…*/}接口C{/*。。。
*/ }
类D{/*…*/}如果未首先指定绑定A,则会出现编译时错误:
类D{/*…*/}//编译时错误
来源:公共接口MyOtherInterface@Zeromus,超级类(或接口)不应该知道基类,这是糟糕的设计。实际的OPs设计可能是XY问题的一个例子。如果您让我们知道您想解决什么而不是如何解决它,那么您的用例可能会使用另一种设计来实现。如何:
MyOtherInterface
?