Scala:在运行时获取混合接口 [英] Scala : get mixin interfaces at runtime
问题描述
我需要在运行时从给定的类中获取所有接口(所有接口都加载到ClassLoader中).
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
我想在运行时获取此信息: A取决于B,C和D . java getInterfaces()(或clapper库中的interfaces())方法仅给出第一个依赖项,即: A依赖于B .
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 ?
推荐答案
这个问题给出了答案:
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
它可以在REPL中使用,但是当我将代码放入Scala脚本文件并执行后,它不再存在:
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
使用weakTypeTag
也不起作用
weakTypeTag[A]
// Runtime error: scala.reflect.internal.FatalError:
// ThisType(free type $anon) for sym which is not a class
Scala 2.10.0、2.10.1和2.11.0-M2的行为相同.
I got the same behaviour with Scala 2.10.0, 2.10.1 and 2.11.0-M2.
这篇关于Scala:在运行时获取混合接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!