我使用scala反射来获取有关模型类中定义的特征的信息.我可以轻松地让这个类的成员这样做:
ru.runtimeMirror(myClassLoader).staticClass("model.Model").typeSignature.members
Run Code Online (Sandbox Code Playgroud)
但是如何知道这些成员是否被定义,即他们是否有实施?
哇这是一个疏忽!我已经提交了一个拉动请求,目标是添加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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
306 次 |
| 最近记录: |