实例化 Scala 中扩展特征的所有类

Lau*_*nti 1 reflection inheritance scala

所以我正在构建一个库,我遇到的问题如下:

我有一个特点,比如

package my.library
trait Animal {
  def randomFunctions
}
Run Code Online (Sandbox Code Playgroud)

我需要知道的是消费者代码具有的所有类,它们扩展/实现了所述特征,例如

package code.consumer
case class Cat extends Animal
case class Dog extends Animal
Run Code Online (Sandbox Code Playgroud)

所以总而言之:在我的库(具有该特征)中,我需要找出扩展/实现该特征的所有类(在消费者代码中)。

Lau*_*nti 5

我最终通过使用反射(https://github.com/ronmamo/reflections)和以下小片段解决了这个问题:

val reflection = new Reflections()
reflection.getSubTypesOf(classOf[Animal])
Run Code Online (Sandbox Code Playgroud)