PropertyUtils类是Apache Commons BeanUtils库中的一个类,用于操作JavaBean对象的属性。
下面是一个使用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: JohnAge: 30这个示例演示了如何使用PropertyUtils类获取和设置JavaBean对象的属性值。通过getProperty方法可以获取属性值,通过setProperty方法可以设置属性值。