복붙노트

[SCALA] 밀봉 특성의 서브 클래스를 얻기

SCALA

밀봉 특성의 서브 클래스를 얻기

이 가능하며 (매크로 통해 달리 자동으로 자료의 엉성한 또는 어떤 형태)는 밀봉 특성의 서브 클래스들의 목록을 얻었다 :

해결법

  1. ==============================

    1.이 작업을 수행 할 수있는 제 3 자 라이브러리가 필요하지 않습니다 :

    이 작업을 수행 할 수있는 제 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)
    

    산출:

  2. from https://stackoverflow.com/questions/34534002/getting-subclasses-of-a-sealed-trait by cc-by-sa and MIT license