「Java」getClass().getDeclaredFields()でクラスのフィールドを取得するサンプル
書式
for (Field field : オブジェクト名.getClass().getDeclaredFields()) {
field.setAccessible(true);
//some code
使用例
1.クラスSampleAの定義
package com.akrgame.study.earn;
import java.math.BigDecimal;
public class SampleA {
private String username;
public int age;
protected BigDecimal price;
//コンストラクター
public SampleA(String username, int gae, BigDecimal price) {
this.username = username;
this.price = price;
this.age = age;
}
}
2.クラスSampleAのフィールドを取得
package com.akrgame.study.earn;
import java.lang.reflect.Field;
import java.math.BigDecimal;
public class FieldInfoGet {
public static void main(String[] args) {
getField();
}
//関数getFieldの定義
public static void getField() {
//オブジェクトの宣言
SampleA tt = new SampleA("user001", 35, new BigDecimal(35.68));
for (Field field : tt.getClass().getDeclaredFields()) {
field.setAccessible(true);
System.out.println("フィールド名前:" + field.getName() + "\n" + "フィールドタイプ:" + field.getType());
}
}
}
実行結果
フィールド名前:username
フィールドタイプ:class java.lang.String
フィールド名前:age
フィールドタイプ:int
フィールド名前:price
フィールドタイプ:class java.math.BigDecimal