外部オブジェクト内で宣言されたオブジェクトを実行時に検出する方法はありますか? JavaClass
メソッドgetClasses
とgetDeclaredClasses
両方が空の配列を返します。
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))
出力は次のとおりです。
Children of Parent:
getClasses found 0
getDeclaredClasses found 0
編集:私は、子供たちに自分自身を親に登録させることを検討しました:
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))
(これは見苦しく見えますが、クリエイティブなサブクラス化と暗黙のパラメーターでこれらの詳細を隠すことができるので、実際には問題ありません。)
このアプローチの問題は、各型が参照されるまで静的初期化子が呼び出されないことです (したがって、Parent.Child1
およびの呼び出しParent.Child2
)。これにより、目的が無効になります。出力は次のとおりです。
(1) Parent.children size: 0
(2) Parent.children size: 2
編集 2:データがそこにあることは知っています! 内部オブジェクトは次を使用してリストされます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 */ }
}
}