Java Kotlin:扩展动态给定的超类型

Java Kotlin:扩展动态给定的超类型,java,generics,kotlin,Java,Generics,Kotlin,假设我有以下课程: class A : SuperType() {} class B : SuperType() {} class C : B() {} 假设我不希望C再扩展B():我希望它扩展A(),但现在我希望A扩展B() 如何在编译时使A扩展B()(或SuperType()的任何子级)而不是仅SuperType()?换句话说,我如何使类A声明成为泛型,以接受SuperType()的任何子类 希望这是清楚的。我想做一些类似的事情: class B(whatever_it_receive

假设我有以下课程:

class A : SuperType() {}

class B : SuperType() {}

class C : B() {}
假设我不希望
C
再扩展
B()
:我希望它扩展
A()
,但现在我希望
A
扩展
B()

如何在编译时使
A
扩展
B()
(或
SuperType()
的任何子级)而不是仅
SuperType()
?换句话说,我如何使类
A
声明成为泛型,以接受
SuperType()的任何子类

希望这是清楚的。我想做一些类似的事情:

class B(whatever_it_receives_as_long_as_child_of_SuperType) : whatever_it_receives_as_long_as_child_of_SuperType()

class C : A(B())    // B is subtype of SuperType so it's ok

您可以执行以下操作:

open class SuperType {}
open class A(val obj: SuperType) : B() {}
open class B : SuperType() {}
class C : A(B())
或使用泛型:

open class SuperType {}
open class A<T: SuperType>(val obj: T) : B() {}
open class B : SuperType() {}
class C : A<B>(B())
开放类超类型{}
开放类A(val obj:T):B(){}
打开类B:超类型(){}
C类:A(B())
如何在编译时生成extend B()(或SuperType()的任何子级)而不是仅生成SuperType()

你不能。每个类只能扩展一个固定的超类

我想你能得到的最接近的是

class A(x: SuperType): SuperType by x
(请参阅)但这需要
超类型
作为接口而不是类