【问题标题】:Access to annotation value in Scala 3.0在 Scala 3.0 中访问注释值
【发布时间】:2021-05-20 17:36:11
【问题描述】:

我在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-reflect 依赖项不再适用于 scala 3.0,因此我们无法访问 runtimeMirror

在 scala 中读取注释值是否有任何替代解决方案?

【问题讨论】:

    标签: scala annotations scala-reflect scala-3


    【解决方案1】:

    您不需要运行时反射(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 中测试

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多