アノテーションを使ってみた
アノテーションを遂に使える局面に当たったので使ってみた。
/** * キー項目に付与するアノテーションです。 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface KeyColumn { }
/** * ユーザテーブルのエンティティです。 */ public class User { @KeyColumn public String userId; public String userName; public String password; }
/** * 引数のエンティティの全てのキー項目を出力します。 */ void printKeys(Object entity) { Field[] fs = entity.getClass().getDeclaredFields(); for(Field f: fs) { if(f.isAnnotationPresent(KeyColumn.class)) { System.out.println(f.get(Object).toString()); } } }