问题
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