如何在 Scala 中定义和使用自定义注解 [英] How to define and use custom annotations in Scala

查看:40
本文介绍了如何在 Scala 中定义和使用自定义注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Scala 中使用自定义注释.在此示例中,我创建了一个要使用元数据进行注释的字符串(在本例中为另一个字符串).然后,给定一个数据实例,我想读取注释.

I am trying use a custom annotation in Scala. In this example, I create a string that I want to annotate with metadata (in this case, another string). Then, given an instance of the data, and I want to read the annotation.

scala> case class named(name: String) extends scala.annotation.StaticAnnotation
defined class named

scala> @named("Greeting") val v = "Hello"
v: String = Hello

scala> def valueToName(x: String): String = ???
valueToName: (x: String)String

scala> valueToName(v) // returns "Greeting" 

这甚至可能吗?

推荐答案

使用 Scala 2.11.6,这可以提取注释的值:

With scala 2.11.6, this works to extract values of a annotation:

case class Named(name: String) extends scala.annotation.StaticAnnotation

val myAnnotatedClass: ClassSymbol = u.runtimeMirror(Thread.currentThread().getContextClassLoader).staticClass("MyAnnotatedClass")
val annotation: Option[Annotation] = myAnnotatedClass.annotations.find(_.tree.tpe =:= u.typeOf[Named])
val result = annotation.flatMap { a =>
  a.tree.children.tail.collect({ case Literal(Constant(name: String)) => doSomething(name) }).headOption
}

这篇关于如何在 Scala 中定义和使用自定义注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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