Is there a way to at runtime discover objects declared inside an outer object? The Java Class
methods getClasses
and getDeclaredClasses
both return empty arrays.
object Parent {
object Child1
object Child2
}
println("Children of Parent:")
println(" getClasses found %d".format(Parent.getClass.getClasses.size))
println(" getDeclaredClasses found %d".format(Parent.getClass.getDeclaredClasses.size))
The output is:
Children of Parent:
getClasses found 0
getDeclaredClasses found 0
EDIT: I have explored having the children register themselves with the parent:
object Parent {
val children = new collection.mutable.ListBuffer[AnyRef]
object Child1 { Parent.children += this }
object Child2 { Parent.children += this }
}
println("(1) Parent.children size: %d".format(Parent.children.size))
Parent.Child1
Parent.Child2
println("(2) Parent.children size: %d".format(Parent.children.size))
(Although this looks ugly, it's actually OK because I can hide these details with creative subclassing and implicit parameters.)
The problem with this approach is the static initializers are not called until each type is referenced (hence the calls to Parent.Child1
and Parent.Child2
), which defeats the purpose. The output is:
(1) Parent.children size: 0
(2) Parent.children size: 2
EDIT 2: I know the data is there! The inner objects are listed using scalap Parent
:
object Parent extends java.lang.Object with scala.ScalaObject {
def this() = { /* compiled code */ }
object Child1 extends java.lang.Object with scala.ScalaObject {
def this() = { /* compiled code */ }
}
object Child2 extends java.lang.Object with scala.ScalaObject {
def this() = { /* compiled code */ }
}
}