获取密封特征的子类

Getting subclasses of a sealed trait

是否有可能(通过宏、某种形式的无形自动魔法或其他方式)获得密封特征的子类列表:

您不需要任何第 3 方库来执行此操作:

sealed trait MyTrait

case object SubClass1 extends MyTrait
case object SubClass2 extends MyTrait

import scala.reflect.runtime.{universe => ru}

val tpe = ru.typeOf[MyTrait]
val clazz = tpe.typeSymbol.asClass
// if you want to ensure the type is a sealed trait, 
// then you can use clazz.isSealed and clazz.isTrait
clazz.knownDirectSubclasses.foreach(println)

输出:

object SubClass1

object SubClass2