Javaで作ったこんなアノテーションがあるとします。
package jp.sf.amateras.sample;
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Id {
}
ケースクラスのプロパティにアノテーションを付与します。
case class Employee(@Id id: Int, name: String)
このアノテーションをJavaのリフレクションを使って読み取ってみます。
val c = classOf[Employee]
// フィールドから取得
val f = c.getDeclaredField("id")
println(f.getAnnotation(classOf[Id])) // => null
// ゲッターメソッドから取得
val m = c.getDeclaredMethod("id")
println(m.getAnnotation(classOf[Id])) // => null
// コンストラクタの引数から取得
val const = c.getConstructors()(0)
val param = const.getParameters()(0)
println(param.getAnnotation(classOf[Id])) // => @jp.sf.amateras.sample.Id()
というわけでコンストラクタの引数から取得することができました。