温馨提示×

Java PropertyUtils类使用实例

小云
79
2023-09-28 09:58:53
栏目: 编程语言

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: John
Age: 30

这个示例演示了如何使用PropertyUtils类获取和设置JavaBean对象的属性值。通过getProperty方法可以获取属性值,通过setProperty方法可以设置属性值。

0