tea-addict tea-addict - 2 months ago 20
Scala Question

Java Annotations javaArgs and LiteralArguments are deprecated

I have problem with Java Annotations because some functions are deprecated and I don't know how to write it with "Annotation.tree" which is suggested.

here is deprecated code:

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]


here is new code which is not working:

lazy val lengthOfAnnotation = p.annotations.find(_.tree.tpe == ru.typeOf[Len])
lazy val maxLength = lengthOfAnnotation.get.tree.children.tail.head.tpe.value.asInstanceOf[Int]


errors:

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

Answer

I found a solution and it is working now.

    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]