Scala 不返回字段的注释 [英] Scala returns no annotations for a field
本文介绍了Scala 不返回字段的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个:
class Max(val value : Int) extends StaticAnnotation{}
class Child() extends Parent {
@Max(5) val myMember= register("myMember")
}
abstract class Parent {
def register(fieldName : String) = {
val cls = getClass
import scala.reflect.runtime.universe._
val mirror = runtimeMirror(cls.getClassLoader)
val clsSymbol = mirror.staticClass(cls.getCanonicalName)
val fieldSymbol = clsSymbol.typeSignature.member(TermName(fieldName))
println(s"${fieldSymbol.fullName} " + fieldSymbol.annotations.size)
}
}
这不起作用,不知何故,它返回 0 个注释,如果相反,我将注释放在类上,那么我可以很好地阅读它.为什么?
this does not work, somehow, it returns 0 annotations, if instead, I put the annotation on the class, then I can read it fine. Why?
推荐答案
发现上一行:
clsSymbol.typeSignature.member(TermName(fieldName))
为val"(当然没有任何注释)返回自动生成的 getter 的符号,而不是 val 本身的符号.如果我这样做:
was returning the symbol of the auto generated getter for the "val" (which of course does not have any annotation), instead of the symbol from the val itself. If instead I do:
clsSymbol.toType.decl(TermName(s"${fieldName} "))
这似乎工作正常.出于我不知道的任何原因,如果我在 TermName 的末尾写一个空格,那么它会返回带有注释的字段符号.
that seems to work fine. For any reason that I do not know, if I write a space at the end of the TermName, then it returns the field symbol with the annotations.
这篇关于Scala 不返回字段的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文