アノテーションを用いたリフレクション
前回記事で元記事の方から反応頂けて恐縮気味です。
書いてて中盤の文章稚拙だなあと思ったましたが、
一日経つと余計に稚拙に見えてしまってちょっと恥ずかしい。
とまあ雑談はこのあたりにして、
Javaで簡単なアノテーション&リフレクション使用例を書いたのでぺたり。
Field.getClass.cast()で変換出来ないかなと思ったのですが、
そう上手く事は運ばず、String→intのキャストはCastExceptionが発生します。
コード簡略化のためgetterメソッドで型変換をしていますが、
型変換のオーバーヘッドが生じるため、
格納元の型がintならInterger.parseInt()を、doubleならDouble.parseDouble()を呼ぶ
といったような分岐処理メソッドを通して格納元に値を詰めるのが良いかと。
public class Main { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface MyAnnotation { public String value(); } public static class Hoge { @MyAnnotation("name") private String user; @MyAnnotation("age") private String age; public String getUser() { return this.user; } public int getAge() { return Integer.parseInt(this.age); } } public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException { Hoge hoge = new Hoge(); // 値の設定 String setData = "name=山田 太郎" + System.getProperty("line.separator") + "age=28"; for (String keyValue : setData.split(System.getProperty("line.separator"))) { String[] temp = keyValue.split("="); String key = temp[0]; String value = temp[1]; for (Field field : hoge.getClass().getDeclaredFields()) { if (key.equals(field.getAnnotation(MyAnnotation.class).value())) { field.setAccessible(true); field.set(hoge, value); } } } // 値の取得 System.out.println(hoge.getUser()); System.out.println(hoge.getAge()); } }
しかし、そのまま編集モードからはてな記法モードに変えると行間変わるのか…。
どこか設定いじれば変えられるのでしょうか?