「Java」PropertyUtils.describe()メソッドでクラスBeanの値をMapに変換する
説明
PropertyUtils.describe
クラスのオブジェクトBeanの各値をMapに変換します。
使用例
1.UserDataクラスの定義
package com.arkgame.study.it;
import java.io.Serializable;
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private Integer age;
private String userName;
private Double price;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
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;
}
}
2.PropertyUtils.describe()メソッドでクラスのメンバーを解析します。
package com.arkgame.study.it;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
public class UserDataDesDemo {
public static void main(String[] args) {
//U
UserData obj = new UserData();
Map<String, Object> mso = describeFunc(obj);
for (String str : mso.keySet()) {
System.out.println("UserDataクラスのメンバー変数: " + str);
}
}
// describeObj
public static Map<String, Object> describeFunc(Object obj) {
Map<String, Object> mp = null;
try {
mp = PropertyUtils.describe(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return mp;
}
}
3.実行結果
UserDataクラスのメンバー変数: price UserDataクラスのメンバー変数: userName UserDataクラスのメンバー変数: age