mardi 7 janvier 2020

How can I reflect on a field annotation (Java) in a Scala program?

I'm using Scala 2.13 and I know there's been a lot deprecated since older versions.

I've got this annotation:

@Inherited
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Foo {
    int index() default 0;
}

(I know... I've got lots of ElementTypes there, but I'm struggling to see where this pops up in reflection so wanted to maximize my chances of a hit!)

Used like this:

case class Person(name: String, @Foo(index = 3) age: Int)
val p = Person("Fred", 29)

How can I reflect on this to get the my Java Annotation (Foo), so I can 1) know whether @Foo exists on a given field, and 2) get the index value. Note I have a declared default value for Foo.index that may be overridden at runtime, so this is a runtime-scoped annotation.





Aucun commentaire:

Enregistrer un commentaire