List all classes in object using reflection

1.3k views Asked by At

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

1

There are 1 answers

1
gysyky On

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]]
  }
}