[英]How perform reflection to find all classes that extend a base class in Scala?
I have a base class of type DataObject which extends other classes. 我有一个DataObject类型的基类,该基类扩展了其他类。 I would like to find all the classes from my main class such that I don't have to import them by hand. 我想从主类中找到所有类,这样就不必手工导入它们。 How can I achieve this? 我该如何实现?
Current implementation (import each class that extends DataObject individually): 当前实现(导入分别扩展DataObject的每个类):
...
val dataObjects: Array[DataObject] = Array(
new ExtendedDataObject(),
new SecondExtendedDataObject(),
.
.
.
new LastExtendedDataObject(),
)
dataObjects.par.foreach(_.doSomething())
...
Example of ideal implementation: 理想实现的示例:
...
def main(args: Array[String]): Unit = {
val dataObjects: Array[DataObject] = <method to find all classes extended by DataObject>
dataObjects.par.foreach(_.doSomething())
}
...
I don't really understand the Scala Reflection Documentation 我不太了解Scala Reflection文档
UPDATE UPDATE
Using org.reflections , how do I turn dataObjects
into Array[DataObject]
? 使用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()
}
...
According to your answers, what you need is: 根据您的答案,您需要的是:
import scala.collection.JavaConverters._
val reflections = new Reflections("my.package.dataobjects")
val dataObjects = asScalaSet(reflections.getSubTypesOf(classOf[Base])).map(_.newInstance())
That's a mutable set of the instances, if you want to make it inmmutable just: 如果您想使其成为不变的,那是一组可变的实例:
val immutableDataObjects = dataObjects.toSet
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.