[英]How to override generic method in scala and call it with reflection
這是我的父母 class
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))
雖然不是類型保存...
看來這就是你想要的
abstract class EntryPoint[C <: Conf]() {
def create(conf: C): Definition
}
class TestEntryPoint extends EntryPoint[EmptyConf] {
override def create(conf: EmptyConf): Definition = ???
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.