Scala : get mixin interfaces at runtime

早过忘川 提交于 2019-12-10 16:00:05

问题


I need to get all the interfaces at runtime from a given Class (all loaded in a ClassLoader).

For instance, if a class has been declared this way :

trait B
trait C
trait D    
class A extends B with C with D

I want to get this information at runtime : A depends on B and C and D. The java getInterfaces() (or the interfaces() from the clapper library) methods gives only the first dependency, namely: A depends on B.

Is there a way to achieve that ?

I guess by reflection but I don't know how ?


回答1:


The solution I found with reflection :

import scala.reflect.runtime.{universe => ru}
val mirror = ru.rootMirror
val t = m.staticClass(classString).typeSignature
t.baseClasses



回答2:


This question gives the answer:

import scala.reflect.runtime.universe._

trait B
trait C
class A extends B with C

val tpe = typeOf[A]
tpe.baseClasses foreach {s => println(s.fullName)}
  // A, C, B, java.lang.Object, scala.Any   


It works in the REPL, but when I put the code into a Scala script file and executed it, it didn't any longer:

typeOf[A]
  // Compiler error: No TypeTag available for this.A

Using weakTypeTag instead didn't help either

weakTypeTag[A]
  // Runtime error: scala.reflect.internal.FatalError:
  // ThisType(free type $anon) for sym which is not a class

I got the same behaviour with Scala 2.10.0, 2.10.1 and 2.11.0-M2.



来源:https://stackoverflow.com/questions/16520057/scala-get-mixin-interfaces-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!