1、定义一个Person类
- package heima.demo;
- public class Person {
-
- private String name;
- private int age;
-
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
复制代码
2、使用BeanUtils
- package heima.demo;
- import org.apache.commons.beanutils.BeanUtils;
- // 内省类
- public class IntrospectorX {
- public static void main(String[] args) throws Exception {
- // 测试用内省的方式读取Person类的 name和age属性;
- // 1)创建Person对象
- Person p = new Person();
- // 定义要获取的属性名
- String name = "name";
- BeanUtils.setProperty(p, name, "Demo");
- Object obj = BeanUtils.getProperty(p, name);
- System.out.println(obj + "\t" + p.getName());
- }
- }
复制代码
注:使用BeanUtils操作的Bean必须被public修饰 |