2016-09-22 61 views
1

我有Java註釋問題,因爲某些函數已被棄用,我不知道如何使用建議的「Annotation.tree」編寫它。Java註釋javaArgs和LiteralArguments已棄用

這裏已經過時代碼:

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 

回答

0

我發現了一個解決方案,它是現在工作。

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]