Java の PropertyUtils クラスの使い方

PropertyUtilsクラスは、JavaBeanオブジェクトのプロパティを操作するApache Commons BeanUtilsライブラリのクラスです。

PropertyUtilsクラスの使い方は以下になります。

import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.PropertyUtils;
public class PropertyUtilsExample {
public static void main(String[] args) {
// 创建一个示例JavaBean对象
Person person = new Person();
person.setName("John");
person.setAge(25);
try {
// 获取并输出name属性的值
String name = (String) PropertyUtils.getProperty(person, "name");
System.out.println("Name: " + name);
// 设置age属性的值为30,并输出
PropertyUtils.setProperty(person, "age", 30);
int age = person.getAge();
System.out.println("Age: " + age);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
// 省略构造方法和其他方法
// name属性的getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// age属性的getter和setter方法
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

上記コードを実行すると、以下の結果が出力されます。

Name: John
Age: 30

PropertyUtilsクラスを使用してJavaBeanオブジェクトの属性値を取得/設定する方法を示すサンプルです。 getPropertyメソッドを使用すると属性値を取得することができ、setPropertyメソッドを使用すると属性値を設定することができます。

bannerAds