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 ?
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)
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$
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