【问题标题】:Finding all classes with specific type查找具有特定类型的所有类
【发布时间】:2015-04-20 18:44:27
【问题描述】:

让我们假设以下设置:

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 = ???

【问题讨论】:

  • 你能把Fruit密封吗?
  • 剧透——如果你不能——那就是impossible;如果可以,那么可以使用宏 stackoverflow.com/questions/13671734/…
  • @Daenyth 不,(但很高兴知道如果它被密封会发生什么)
  • 您是要在运行时还是在代码编辑时获取此列表?你想解决什么问题?
  • 如果您在代码编辑时需要它,您可以在 eclipse 中按 ctrl+t 或在 intellij 中按 ctrl+h。这应该显示类层次结构(包括所有扩展类)。附言我没有安装 IDEA,所以我只记得。

标签: scala


【解决方案1】:

如果你不能上课sealed

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

看起来有一个名为 reflections 的 java 库提供了一种方法:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 2013-01-04
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    相关资源
    最近更新 更多