Skip to content

Instantly share code, notes, and snippets.

@takezoe
Last active August 29, 2015 14:03
Show Gist options
  • Save takezoe/91f837924baf2f83fd6e to your computer and use it in GitHub Desktop.
Save takezoe/91f837924baf2f83fd6e to your computer and use it in GitHub Desktop.
Scalaのケースクラスのプロパティに付けたアノテーションを読み取る

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()

というわけでコンストラクタの引数から取得することができました。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment