How to define and use custom annotations in Scala

倖福魔咒の 提交于 2021-02-07 05:30:15

问题


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" 

Is this even possible?


回答1:


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
}



回答2:


There are different kinds of annotations in Scala:

Java Annotations that you can access using the Java Reflection API, annotations that are just in the source code, static annotations that are available to the type checker across different compilation units (so they should be somewhere in a class file but not where normal reflections go) and classfile annotations which are stored like java annotations, but cannot be read using the java reflection api.

I have described how to access static and classfile annotations here: What is the (current) state of scala reflection capabilities, especially wrt annotations, as of version 2.11?

If you just need a annotation containing a string using a Java annotation that is loaded by the JVM for you might be the simpler alternative.



来源:https://stackoverflow.com/questions/35420334/how-to-define-and-use-custom-annotations-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!