How to use scala reflection API to get all contained classes

后端 未结 2 625
小蘑菇
小蘑菇 2020-12-14 12:05

I got this kind of class:

trait ThirdParty { def invoke = println(\"right\") }

trait WeatherIcon { def invoke = println(\"wrong\") }

class MyClass {

    o         


        
2条回答
  •  温柔的废话
    2020-12-14 12:06

    I can't offer a complete solution, but maybe this is a start:

    import reflect.runtime.universe._
    
    val myClassType = typeOf[MyClass]    // Get the type of McClass
    val thirdPartyType = typeOf[ThirdParty] // Get the type of ThirdParty
    val methodToInvoke = newTermName("invoke")
    
    val declsOfMyClass = myClassType.declarations // Get the declarations of MyClass
    
    val subtypesOfThirdParty = 
      declsOfMyClass.filter(_.typeSignature.parents.contains(thirdPartyType))
    
    val methodsToInvoke =             // Now we have the methods.
      subtypesOfThirdParty.map(tps => tps.typeSignature.member(methodToInvoke))
    
    // TODO: Invoke!
    

    I guess there is a much more straight-forward way than this.

提交回复
热议问题