Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect inner objects in a scala object

I want to get a list of inner objects of a scala object. Sample code:

object Outer {
  val v = "-"
  def d = "-"
  object O1
  object O2
}

object Main {
  def main(args: Array[String]) {
    Outer.getClass.getDeclaredMethods.map(_.getName) foreach println  // prints d and v
    // Outer.getClass.get ... Objects???
  }
}

I can find v and d, but how can I find O1 and O2 ?

like image 757
stackunderflow Avatar asked Jun 05 '12 08:06

stackunderflow


2 Answers

With the new reflection library in Scala 2.10 (since Milestone 4) it is possible to get the inner objects:

scala> import scala.reflect.runtime.{universe => u}
import scala.reflect.runtime.{universe=>u}

scala> val outer = u.typeOf[Outer.type]
outer: reflect.runtime.universe.Type = Outer.type

scala> val objects = outer.declarations.filter(_.isModule).toList
objects: List[reflect.runtime.universe.Symbol] = List(object O1, object O2)
like image 92
kiritsuku Avatar answered Oct 29 '22 18:10

kiritsuku


Object O1 and O2 are nested classes and are not a part of Outer Object.

    println(Outer.O1.getClass.getName) //Outer$O1$
    println(Outer.getClass.getName)    //Outer$
    println(Outer.O2.getClass.getName) //Outer$O2$
like image 32
Prince John Wesley Avatar answered Oct 29 '22 18:10

Prince John Wesley