我在使用 Java 注释时遇到问题,因为某些函数已被弃用,而且我不知道如何使用建议的“Annotation.tree”来编写它。
这里是已弃用的代码:
lazy val lengthOfAnnotation = p.annotations.find(_.tpe == ru.typeOf[Len])
lazy val maxLength = lengthOfAnnotation.get.javaArgs.head._2.asInstanceOf[ru.LiteralArgument].value.value.asInstanceOf[Int]
这是不起作用的新代码:
lazy val lengthOfAnnotation = p.annotations.find(_.tree.tpe == ru.typeOf[Len])
lazy val maxLength = lengthOfAnnotation.get.tree.children.tail.head.tpe.value.asInstanceOf[Int]
错误:
method javaArgs in trait AnnotationApi is deprecated: Use tree.children.tail instead
type LiteralArgument in trait Annotations is deprecated: Use Annotation.tree to inspect annotation arguments
method value in trait LiteralArgumentApi is deprecated: Use Annotation.tree to inspect annotation arguments
我找到了一个解决方案,它现在正在运行。
import scala.reflect.runtime._
import scala.reflect.runtime.universe._
lazy val lengthOfAnnotation = p.annotations.find(_.tree.tpe == ru.typeOf[Len])
val result = lengthOfAnnotation.flatMap { a =>
a.tree.children.tail.head.collect({ case Literal(Constant(value)) => value }).headOption
}
lazy val maxLength = result.get.value.asInstanceOf[Int]
我是一名优秀的程序员,十分优秀!