Scala不为字段返回任何注释 [英] Scala returns no annotations for a field

查看:57
本文介绍了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"的吸气剂的符号(它当然没有任何注释),而不是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆