「Java」BeanUtils.describeメソッドでクラスBeanの全フィールドを取得するサンプル
構文
BeanUtils.describe(オブジェクト名).keySet().iterator()
Iterator<E> iterator()
セット内の各要素についてのイテレータを返します。セットが順序を保証する特定クラスのインスタンスでないかぎり、
要素は特定の順序では返されません。
使用例
1.EmployeeDataクラスの定義
package com.arkgame.study.it;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import org.apache.commons.beanutils.BeanUtils;
public class EmployeeData implements Serializable {
private static final long serialVersionUID = 1L;
private String userName;
private Double price;
private int age;
// constructor
public EmployeeData(String userName, Double price, int age) {
this.userName = userName;
this.price = price;
this.age = age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Iterator<?> getNames(EmployeeData obj) {
try {
return BeanUtils.describe(obj).keySet().iterator();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
}
2.getNames()でクラスのフィールドを取得
package com.arkgame.study.it;
import java.util.Iterator;
public class EmpDataBeanBeanUtils {
public static void main(String[] args) {
EmployeeData cftData = new EmployeeData("employee", 21.35, 32);
Iterator<?> prop;
prop = cftData.getNames(cftData);
System.out.println("クラスのフィールド下記:");
while (prop.hasNext()) {
System.out.println(prop.next());
}
}
}
クラスのフィールド下記:
price
userName
age