访问 Scala 3.0 中的注释值

问题描述

我在scala中创建了注解并使用如下:

object Main extends App {
  println(classOf[Annotated].getAnnotations.length)

  import scala.reflect.runtime.universe._
  val mirror = runtimeMirror(cls.getClassLoader)

}


final class TestAnnotation extends StaticAnnotation

@TestAnnotation
class Annotated

另一方面,由于它是 Scala 注释,因此无法使用 getAnnotations 读取,因此 Scala 3.0 不再提供 scala-reflect 依赖项,因此我们无法访问 runtimeMirror

是否有其他解决方案可以读取 Scala 中的注释值?

解决方法

您不需要运行时反射(Java 或 Scala),因为有关注释的信息存在于编译时(即使在 Scala 2 中)。

在 Scala 3 中,您可以编写 macro 并使用 TASTy reflection

import scala.quoted.*

inline def getAnnotations[A]: List[String] = ${getAnnotationsImpl[A]}

def getAnnotationsImpl[A: Type](using Quotes): Expr[List[String]] = {
  import quotes.reflect.*
  val annotations = TypeRepr.of[A].typeSymbol.annotations.map(_.tpe.show)
  Expr.ofList(annotations.map(Expr(_)))
}

用法:

@main def test = println(getAnnotations[Annotated]) // List(TestAnnotation)

在 3.0.0-RC2-bin-20210217-83cb8ff-NIGHTLY 中测试