Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all classes in object using reflection

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

like image 565
gysyky Avatar asked Jan 10 '23 08:01

gysyky


1 Answers

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]]
  }
}
like image 186
gysyky Avatar answered Jan 11 '23 22:01

gysyky