I have an object like:
sealed trait Message
object Message {
case class DoSomething(...) extends Message
case class DoSomethingElse(...) extends Message
...
}
what I'm trying to do is to create a list of all Messages in Message object.
What I have so far is:
val messages: Iterable[Class[_ <: Message]] = {
import scala.reflect.runtime.universe._
val mirror = runtimeMirror(this.getClass.getClassLoader).reflect(Message)
typeOf[Message.type].decls.collect {
case c: ClassSymbol if c.toType <:< typeOf[Message] =>
mirror.reflectClass(c).symbol.getClass.asInstanceOf[Class[_ <: Message]]
}
}
But it yields not very informative error for me:
scala.ScalaReflectionException: class DoSomething is a static class, use reflectClass on a RuntimeMirror to obtain its ClassMirror
As far as I see, I'm using reflectClass
on RuntimeMirror
. Am I missing something?
Thanks
After having much more reading about Scala reflections, being richer in knowledge, I found the solution. All I needed was:
val messages = {
import scala.reflect.runtime.universe._
val mirror = runtimeMirror(this.getClass.getClassLoader)
typeOf[Message.type].decls.collect {
case c: ClassSymbol if c.toType <:< typeOf[Message] =>
mirror.runtimeClass(c).asInstanceOf[Class[_ <: Message]]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With