查找具有特定类型的所有类

时间:2015-04-20 18:44:27

标签: scala

我们假设以下设置:

trait Fruit{
def name:String
}

trait Fruit2 extends Fruit{
def name:String
}

case class Apple(name:String) extends Fruit
case class Pear(name:String) extends Fruit
case class Dragon-fruit(name:String) extends Fruit2

trait Color
case class ColoredApple[C](name String) extends Fruit

case class Red extends Color
val RedApple = ColoredApple[Red]("red apple")
val ...

首先,是否有任何方式而不是反射来获得所有Fruit类? 如何使用/不使用反射获取这些类和变量的列表(例如所有带有红色的ColoredApple)?像这样的东西:

val allRedApples = ???

1 个答案:

答案 0 :(得分:1)

如果你不能让你的课程sealed

,那么如果没有反思就无法做到这一点

它也not possible可以获得完整而准确的结果。

看起来像是一个名为reflections的java库提供了一种方式:

Reflections reflections = new Reflections("my.project");

Set<Class<? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class);