我有一个DataObject类型的基类,该基类扩展了其他类。我想从主类中找到所有类,这样就不必手工导入它们。我该如何实现?
当前实现(导入分别扩展DataObject的每个类):
...
val dataObjects: Array[DataObject] = Array(
new ExtendedDataObject(),
new SecondExtendedDataObject(),
.
.
.
new LastExtendedDataObject(),
)
dataObjects.par.foreach(_.doSomething())
...
理想实现的示例:
...
def main(args: Array[String]): Unit = {
val dataObjects: Array[DataObject] = <method to find all classes extended by DataObject>
dataObjects.par.foreach(_.doSomething())
}
...
我不太了解Scala Reflection Documentation
更新
如何使用org.reflections将dataObjects
变成Array[DataObject]
?
...
def main(args: Array[String]): Unit = {
val reflections = new Reflections("my.package.dataobjects")
val dataObjects = reflections.getSubTypesOf(classOf[DataObject]).toArray()
}
...
答案 0 :(得分:1)
根据您的答案,您需要的是:
import scala.collection.JavaConverters._
val reflections = new Reflections("my.package.dataobjects")
val dataObjects = asScalaSet(reflections.getSubTypesOf(classOf[Base])).map(_.newInstance())
这是可变的一组实例,如果您只想使它们不变:
val immutableDataObjects = dataObjects.toSet