10

I use scala reflection to get information on a trait defined in my Model Class. I can easily get the members of this class doing this:

ru.runtimeMirror(myClassLoader).staticClass("model.Model").typeSignature.members

but how to know whether these members are defined or not, ie if they have an implementation or not ?

4

1 回答 1

8

哇,这是一个疏忽!我已经提交了一个针对 2.11.0 ( https://github.com/scala/scala/pull/2612 ) 的拉取请求,其中添加了Symbol.isAbstract.

由于这是一个新的 API,由于兼容性限制,它无法进入 2.10.x,所以同时请使用以下解决方法:

00:01 ~/Projects/210x (2.10.x)$ scala
Welcome to Scala version 2.10.3-20130527-133534-9b310bc906 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_45).
Type in expressions to have them evaluated.
Type :help for more information.

scala> trait C { def foo: Int; def bar = 2 }
defined trait C

scala> val foo = typeOf[C].declarations.toList.apply(1)
foo: reflect.runtime.universe.Symbol = method foo

scala> val bar = typeOf[C].declarations.toList.apply(2)
bar: reflect.runtime.universe.Symbol = method bar

scala> def isDeferred(sym: Symbol) = sym
         .asInstanceOf[scala.reflect.internal.Symbols#Symbol]
         .hasFlag(scala.reflect.internal.Flags.DEFERRED)
isDeferred: (sym: reflect.runtime.universe.Symbol)Boolean

scala> isDeferred(foo)
res2: Boolean = true

scala> isDeferred(bar)
res3: Boolean = false
于 2013-05-29T22:03:32.390 回答