How to access Annotation defined on case class field at Runtime

前端 未结 3 448
逝去的感伤
逝去的感伤 2021-01-04 10:52

I\'ve the following java Annotation defined

   @Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.FIELD})
   @Retenti         


        
3条回答
  •  醉酒成梦
    2021-01-04 11:54

    Quentin's solution worked, but IMHO it's too much boilerplate for the user.

    You can read annotations on the constructor arguments with the standard reflection API. I needed this for a macro implementation.

    scala> :paste
    // Entering paste mode (ctrl-D to finish)
    
    import scala.annotation.StaticAnnotation
    final class min(i: Long) extends StaticAnnotation
    
    case class Foo(@min(1) c: String)
    import scala.reflect.runtime.universe._
    symbolOf[Foo].asClass.primaryConstructor.typeSignature.paramLists.head.head.annotations
    
    // Exiting paste mode, now interpreting.
    
    import scala.annotation.StaticAnnotation
    defined class min
    defined class Foo
    import scala.reflect.runtime.universe._
    res0: List[reflect.runtime.universe.Annotation] = List(min(1L))
    

提交回复
热议问题