让我们假设一个控制器对象是这样的:
object Users extends Controller {
...
@ApiOperation(
httpMethod = "POST",
nickname = "authenticate",
value = "Authenticates an user",
notes = "Returns the JSON Web Token to be used in any subsequent request",
response = classOf[models.auth.api.Jwt])
def authenticate = SecuredAction[Users.type]("authenticate").async(parse.json) { implicit request =>
...
}
...
}
如何authenticate
在运行时获取方法的注释值?我试过这个:
def methodAnnotations[T: TypeTag]: Map[String, Map[String, Map[String, JavaArgument]]] = {
typeTag[T].tpe.declarations.collect { case m: MethodSymbol => m }.map { m =>
val methodName = m.name.toString
val annotations = m.annotations.map { a =>
val annotationName = a.tpe.typeSymbol.name.toString
val annotationArgs = a.javaArgs.map {
case (name, value) => name.toString -> value
}
annotationName -> annotationArgs
}.toMap
methodName -> annotations
}.toMap
}
methodAnnotations
返回指定方法的指定注解并像这样调用:
val mAnnotations = methodAnnotations[T]
val nickname = mAnnotations("myMethodName")("MyAnnotationName")("myAnnotationMemberName").asInstanceOf[LiteralArgument].value.value.asInstanceOf[String]
问题是当我编译上面的代码时,我总是收到以下警告:
type JavaArgument in trait Annotations is deprecated: Use `Annotation.tree` to inspect annotation arguments
method tpe in trait AnnotationApi is deprecated: Use `tree.tpe` instead
使用 scala 2.11 获取方法注释的正确方法是什么?