2

I created annotation in scala and used it as follows:

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

As it's a Scala annotation it can not be read using getAnnotations on the other hand, scala-reflect dependency isn't available anymore for scala 3.0, so we have no access to runtimeMirror

Is there any alternative solution to read an annotation value in scala?

Nik Kashi
  • 4,447
  • 3
  • 40
  • 63

1 Answers1

2

You don't need runtime reflection (Java or Scala) since information about annotations exists at compile time (even in Scala 2).

In Scala 3 you can write a macro and use 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(_)))
}

Usage:

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

Tested in 3.0.0-RC2-bin-20210217-83cb8ff-NIGHTLY

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • https://github.com/typelevel/shapeless-3/blob/main/modules/deriving/src/main/scala/shapeless3/deriving/annotation.scala – Dmytro Mitin Oct 10 '21 at 16:03
  • https://github.com/evolution-gaming/derivation/blob/5bff9cb72e6d68a90d3e57bbcc352103e295108d/modules/core/src/main/scala/evo/derivation/config/ConfigMacro.scala https://contributors.scala-lang.org/t/expose-type-annotations-in-mirrors/5936 – Dmytro Mitin Dec 11 '22 at 15:21