简体   繁体   English

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

[英]How to override generic method in scala and call it with reflection

Here is my parent class这是我的父母 class


sealed trait Conf
sealed case class EmptyConf(value:String) extends Conf

abstract class EntryPoint() {
  def create[C <: Conf](conf: C): Definition
}

Here is the child这里是孩子

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

Compiler says:编译器说:

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

What do I do wrong?我做错了什么?

UPD: I tried UPD:我试过了

abstract class EntryPoint[C <: Conf]() {
  def create(conf: C): Definition
}

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

Then I have troubles instantiating it using reflection.然后我在使用反射实例化它时遇到了麻烦。

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

It won't compile since create expects subclass of Conf .它不会编译,因为create需要Conf的子类。 How can I get it in runtime?如何在运行时获取它?

UPD: It works, thank you. UPD:它有效,谢谢。 Just add some bruteforce只需添加一些蛮力

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))

Not type-save though...虽然不是类型保存...

It seems that this is what you want看来这就是你想要的

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM