我在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
依赖已不再斯卡拉3.0可用,所以我们都进不去runtimeMirror
是否有其他解决方案可在Scala中读取注释值?
您不需要运行时反射(Java或Scala),因为有关注释的信息在编译时就存在(即使在Scala 2中也是如此)。
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中测试
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句