0
来自StackOverflow的Scala专家。我可以从Scala中的注释成员测量注释泛型类型吗?
在示例代码下面,我重现了我正在处理的一个项目上的行为。我应该能够推断/测量当它出现在类字段成员中时定义的注释“武器”泛型类型。
import scala.reflect.runtime.universe._
import scala.annotation.StaticAnnotation
class Reflection
object Reflection {
def reflect[T: TypeTag](x: Class[T]): Type = {
typeOf[T]
}
def main(args: Array[String]) {
var tpe = reflect(classOf[Hero])
for (member <- tpe.members)
for (annotation <- member.annotations)
annotation.tpe match {
case t if t <:< typeOf[weapon[_]]
=> println(s"found weapon member: $member")
case t if t <:< typeOf[action]
=> println(s"found action member: $member")
}
}
}
class weapon[T <: WeaponType](x: String = null) extends StaticAnnotation
class action extends StaticAnnotation
class WeaponType(damage: Int)
case class Knife extends WeaponType(12)
class Hero {
@weapon[Knife] var weapon: String = _
@action def hitWithKnife() {
}
}
然而,在我提供的示例代码,我可能无法避免REPL打印一个奇怪的日志作为
[] ?_$1 setInst sample.Knife
在此先感谢
编辑
'@alexwriteshere'正确地解释了日志让我无聊的原因。他让我觉得我的问题很困惑。
问题
它可以推断/测量在一类构件上@weapon定义的T形(如在武器部件从我的英雄类看到的)。
感谢您的快速解释。我正在寻找这个日志问题没有成功。但是我想推断我的英雄类中的@weapon上设置的T类型。我想我没有解释这个问题。 – Miere
添加了获取注释参数的方式。这是你在找什么? –
很多谢谢老兄!有用。 – Miere