如何覆盖scala中的泛型方法并使用反射调用它



这是我的父类


sealed trait Conf
sealed case class EmptyConf(value:String) extends Conf
abstract class EntryPoint() {
def create[C <: Conf](conf: C): Definition
}

这是儿童

class TestEntryPoint extends EntryPoint {
override def create(conf: EmptyConf): Definition = ???
}

编译器说:

class TestEntryPoint needs to be abstract, 
since method create in class EntryPoint of type [C <: Conf](conf: C)Definition 
is not defined

我做错了什么?

UPD:我试过

abstract class EntryPoint[C <: Conf]() {
def create(conf: C): Definition
}
class TestEntryPoint extends EntryPoint[EmptyConf] {
override def create(conf: EmptyConf): Definition = ???
}

然后我在使用反射实例化它时遇到了麻烦。

private def instantiate[P <: EntryPoint[_]](entryPointClass: Class[P],
conf: Conf): Definition = {
entryPointClass.getConstructor()
.newInstance()
.create(conf)
}

它不会编译,因为create需要Conf的子类。如何在运行时获得它?

UPD:它有效,谢谢。只需在之前添加一些野兽

entryPointClass.getDeclaredMethods
.find(_.getName == "create")
.map(_.invoke(instance, conf))
.map(_.asInstanceOf[Definition])
.getOrElse(throw DefinitionInstantiationException(
s"Can't instantiate ${entryPointClass.getName} " +
s"using configuration ${conf.getClass.getName}",
new RuntimeException))

但没有键入save。。。

这似乎就是您想要的

abstract class EntryPoint[C <: Conf]() {
def create(conf: C): Definition
}
class TestEntryPoint extends EntryPoint[EmptyConf] {
override def create(conf: EmptyConf): Definition = ???
}

最新更新