Java Kotlin在抽象类中调用伴生对象
我有一个类,Java Kotlin在抽象类中调用伴生对象,java,kotlin,Java,Kotlin,我有一个类,Base,它是一个抽象类,定义如下: abstract class Base() {} 我想从这个基类创建几个派生类: class A : Base() {} class B : Base() {} class C : Base() {} 我希望能够调用一个公共函数create,该函数执行一些初始化工作并返回指定的派生类(例如a)。例如,下面这样的内容将是理想的: val a = A.create() // `a` now holds an instance of `A`. va
Base
,它是一个抽象类,定义如下:
abstract class Base() {}
我想从这个基类创建几个派生类:
class A : Base() {}
class B : Base() {}
class C : Base() {}
我希望能够调用一个公共函数create
,该函数执行一些初始化工作并返回指定的派生类(例如a
)。例如,下面这样的内容将是理想的:
val a = A.create() // `a` now holds an instance of `A`.
val b = B.create()
val c = C.create()
最初,我尝试在抽象类中使用一个伴生对象作为一种静态函数:
abstract class Base {
companion object {
fun create() : Base {
// Do some initialization and return the derived class
// of the object. Obviously I can't return `Base` as I've
// indicated above since it is an abstract class. This is
// what I'm confused about: How do I return a copy of the
// _derived_ class here? Is this impossible? I think it
// might be...
return Base() // <-- This doesn't work. What should be returned?
}
}
}
这不起作用,原因很明显。也就是说,我不能返回抽象类
Base
的实例。是否有一种简单的方法来完成var a=a.create()
范例?create
的代码在派生类中是相同的,因此我希望避免在我创建的每个类中重新创建功能。如果初始化逻辑相同,并且基于Base
类中指定的功能,您也可以这样做:
abstract class Base {
companion object {
inline fun <reified T : Base> create() : T {
// you can use T::class here
}
}
}
class A : Base() {
companion object {
fun create() : A = Base.create() // inferred to Base.create<A>()
}
}
abstract class Base() {
protected fun init(): Base {
// do the initialization
return this
}
}
class A : Base() {
companion object {
fun create() = A().init() as A
}
}
“create的代码在派生类中是相同的”那么,这怎么可能呢?如果代码完全相同,那么返回类型也完全相同。@AlexeyRomanov这就是我要说的。返回类型是从
Base
继承的。也许更好的说法是“创建<代码>的样板代码每次都需要做相同的事情,但是对于不同的派生类”。我不能使返回类型Base
,因为这意味着要创建派生类的实例。谢谢!基于这个答案,我可以创建我自己的内联具体化的伴奏函数来创建我的项目实例,而不需要不安全的反射!
abstract class Base {
companion object {
inline fun <reified T : Base> create(f: () -> T) : T {
val instance = f()
// do something
return instance // or something created from it
}
}
}
class A : Base() {
companion object {
fun create() : A = Base.create { A() }
}
}
abstract class Base() {
protected fun init(): Base {
// do the initialization
return this
}
}
class A : Base() {
companion object {
fun create() = A().init() as A
}
}