lundi 31 août 2020

How to access scala annotation in scala code

I have defined a simple scala annoation and use it to annotate my case class Person:

package com.my

import  scala.annotation.StaticAnnotation

@scala.annotation.meta.field
class Description(value: String) extends StaticAnnotation{

}

Then I use it in my Person class:

package com.my

import scala.beans.BeanProperty

case class Person(

                   @Description(value = "name00")
                   name: String,

                   @Description(value = "age00")
                   age: Int,

                   @BeanProperty
                   xyz: String = "xyz"
                 )

object Person {
  def main(args: Array[String]): Unit = {
    val p = Person("abc", 21)
    classOf[Person].getDeclaredFields.foreach {
      field =>
        field.setAccessible(true)
        val name = field.getName
        val value = field.get(p)
        //annotations always return empty array
        val annotations = field.getDeclaredAnnotations
        annotations.foreach {
          annotation =>
            val tpe = annotation.annotationType()
            println(tpe)
        }
        println(s"name is $name, value is: $value")
    }
  }
}

In the main method of Person object, the annotations array is always empty, I would like to ask how to get the annoation information defined on the field.





Aucun commentaire:

Enregistrer un commentaire