「Java」PropertyUtils.getPropertyでBeanクラス内の属性を取得する
関数
1.setProperty(bean, name, value)
bean内のnameにvalueをセットします。
戻り値:void
2.getProperty(bean, name)
bean内のnameの値を返します
戻り値:Object
使用例
1.Userクラスの定義
package com.arkgame.study;
public class User {
private Integer age = null;
private String userId = null;
private String addr = null;
public User(Integer age, String userId, String addr) {
super();
this.age = age;
this.userId = userId;
this.addr = addr;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}
2.Userクラスに対してPropertyUtils.setPropertyとPropertyUtils.getPropertyの操作
package com.arkgame.study;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.PropertyUtils;
public class SetPropertyDemo {
public static void main(String[] args) {
User userA = new User(21, "user001", "test addressA");
try {
// プロパティ(age)の設定
PropertyUtils.setProperty(userA, "age", 32);
// プロパティ(userId)の設定
PropertyUtils.setProperty(userA, "userId", "54321");
// プロパティ(addr)の設定
PropertyUtils.setProperty(userA, "addr", "tokyo shinagawa");
// プロパティのuserId取得
Object userId = PropertyUtils.getProperty(userA, "userId");
System.out.println("「userId Value」: " + userId.toString());
// プロパティのaddr取得
Object addr = PropertyUtils.getProperty(userA, "addr");
System.out.println("「address Value」: " + addr.toString());
// プロパティのage取得
Integer age = (Integer) PropertyUtils.getProperty(userA, "age");
System.out.println("「age Value」: " + age.toString());
} catch (IllegalAccessException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
}
実行結果
「userId Value」: 54321 「address Value」: tokyo shinagawa 「age Value」: 32