Here is my parent 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
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
. How can I get it in runtime?
UPD: It works, thank you. 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 = ???
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.