8

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 ?

2
  • Object O1 and O2 are nested classes and are not a part of Outer. You need to access like Outer.O1.getClass.. Jun 5, 2012 at 8:12
  • Thank you for your answer, but I wan't to get them as a List in a generic way (without knowing their names before). I'm searching for somithing like the getDeclaredMethods method in the example. Jun 5, 2012 at 11:27

2 Answers 2

8

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)
0
1

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$
2
  • 2
    Thank you for your answer, but I wan't to get them as a List in a generic way (without knowing their names before). I'm searching for somithing like the getDeclaredMethods method in the example. Jun 5, 2012 at 11:27
  • You can't do that. nested Object/class is not a part of the enclosing object. Jun 5, 2012 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.