「Java」getDeclaredFields() メソッドでクラスの全てフィールド(メンバ変数)を取得する方法
説明
public Field[] getDeclaredFields()throws SecurityException
このClassオブジェクトが表すクラスまたはインタフェースによって宣言されたすべての
フィールドをリフレクトするFieldオブジェクトの配列を返します。
1.FieldDemoクラスの定義
package com.arkgame.study.java;
import java.lang.reflect.Field;
public class FieldDemo {
//parameter definition
String username = "007user";
Integer age = 25;
Boolean flg = false;
//constructor definition
public FieldDemo(String username, Integer age, Boolean flg) {
this.username = username;
this.age = age;
this.flg = flg;
}
//method definition
public String getFieldName()
throws IllegalArgumentException, IllegalAccessException {
StringBuilder sb = new StringBuilder();
// Fieldオブジェクトの配列
Field[] cftFd = this.getClass().getDeclaredFields();
for (Field fd : cftFd) {
// フィールドの名前 フィールドの値
sb.append("フィールド名: " + fd.getName() + " 値: " + fd.get(this) + "\n");
}
return sb.toString();
}
}
2.FieldDemoクラスのメンバーを取得する
package com.arkgame.study.java;
public class FieldGet {
public static void main(String[] args)
throws IllegalArgumentException, IllegalAccessException {
// FieldDemo オブジェクト宣言
FieldDemo fieldDemoObj = new FieldDemo("user001", 30, true);
String fieldName;
// getFieldNameメソッドを呼び出す
fieldName = fieldDemoObj.getFieldName();
System.out.println("クラスの全てフィールドの名前と値:\n" + fieldName);
}
}
3.実行結果
クラスの全てフィールドの名前と値:
フィールド名: username 値: user001
フィールド名: age 値: 30
フィールド名: flg 値: true