【commons-beanutils专题】003- PropertyUtils 专题

【commons-beanutils专题】003- PropertyUtils 专题

文章目录

一、准备

0、PropertyUtils 主要作用

主要用于通过反射技术操作对象的属性:获取属性、设置属性、获取属性描述、浅拷贝等

1、引入 commons-beanutils 依赖

<!--引入依赖commons-beanutils-->
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

2、pom.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zibo</groupId>
    <artifactId>zibo2022</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>zibo2022</name>
    <description>zibo2022</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--引入依赖commons-beanutils-->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.7.1</version>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

3、实体类

package com.zibo.zibo2022.property_utils.entity;

import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author zibo
 * @date 2022/7/14 0014 18:41
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {

    /**
     * 名字
     */
    private String name;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 地址
     */
    private String address;

    /**
     * 朋友
     */
    private Friend friend;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Friend {

        private String name;

        private Integer age;

        private String address;

    }

    /**
     * 爱好
     */
    private List<String> hobbies;

    /**
     * 学校
     */
    private Map<String, String> schoolMap;

}

4、前置代码

Map<String, String> schoolMap = new HashMap<>();
schoolMap.put("高中", "某高中");
schoolMap.put("大学", "某大学");
Student student = new Student("訾博", 22, "北京", new Student.Friend("刘备", 26, "北京"), Arrays.asList("篮球", "足球"), schoolMap);

二、暂时不知道有什么用的功能

1、清空所有属性的描述信息

// 1、清空所有属性的描述信息
// 说明:清除任何类加载器加载的所有类的任何缓存属性描述符信息。这在丢弃类加载器以实现类重新加载的情况下很有用。
PropertyUtils.clearDescriptors();

2、重置 BeanIntrospectors 的缓存属性描述符信息

// 2、重置 BeanIntrospectors 的缓存属性描述符信息
// 说明:将注册的 BeanIntrospector 对象重置为初始默认状态。
PropertyUtils.resetBeanIntrospectors();

3、添加一个 BeanIntrospector

// 3、添加一个 BeanIntrospector
// 说明:添加一个 BeanIntrospector ,当需要获取类的属性描述符时调用该对象。
PropertyUtils.addBeanIntrospector(DefaultBeanIntrospector.INSTANCE);

4、移除一个 BeanIntrospector

// 4、移除一个 BeanIntrospector
// 说明:移除指定的 BeanIntrospector 。
BeanIntrospector instance = DefaultBeanIntrospector.INSTANCE;
PropertyUtils.removeBeanIntrospector(instance);

三、浅拷贝

// 5、复制属性
// 说明:经测试这是一种浅拷贝!
try {
    Student student1 = new Student();
    // 参数:目标对象,源对象
    PropertyUtils.copyProperties(student1, student);
    System.out.println(student);
    // Student(name=訾博, age=22, address=北京, friend=Student.Friend(name=刘备, age=26, address=北京), hobbies=[篮球, 足球], schoolMap={大学=某大学, 高中=某高中})
    System.out.println(student1);
    // Student(name=訾博, age=22, address=北京, friend=Student.Friend(name=刘备, age=26, address=北京), hobbies=[篮球, 足球], schoolMap={大学=某大学, 高中=某高中})
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

四、获取对象的属性描述

// 6、获取属性描述
// 说明:经测试发现,含所有属性和 class 属性
try {
    Map<String, Object> map = PropertyUtils.describe(student);
    map.forEach((key, value) -> System.out.println(key + ":" + value));
    // address:北京
    // hobbies:[篮球, 足球]
    // friend:Student.Friend(name=刘备, age=26, address=北京)
    // name:訾博
    // schoolMap:{大学=某大学, 高中=某高中}
    // class:class com.zibo.zibo2022.property_utils.entity.Student
    // age:22
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

五、获取属性值

1、指定索引属性值,适用于属性是 list 或 array 的情况

// 7、指定索引属性值,适用于属性是 list 或 array 的情况
try {
    Object property = PropertyUtils.getIndexedProperty(student, "hobbies[0]");
    System.out.println(property); // 篮球
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

2、指定索引属性值,适用于属性是 list 或 array 的情况

// 8、指定索引属性值,适用于属性是 list 或 array 的情况
try {
    Object property = PropertyUtils.getIndexedProperty(student, "hobbies", 1);
    System.out.println(property); // 足球
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

3、获取 map 属性,适用于属性是 map 的情况

// 9、获取 map 属性,适用于属性是 map 的情况
try {
    Object property = PropertyUtils.getMappedProperty(student, "schoolMap(高中)");
    System.out.println(property); // 某高中
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

4、获取 map 属性,适用于属性是 map 的情况

// 10、获取 map 属性,适用于属性是 map 的情况
try {
    Object property = PropertyUtils.getMappedProperty(student, "schoolMap", "大学");
    System.out.println(property); // 某大学
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

5、获取嵌套属性,属性是对象的情况

// 11、获取嵌套属性,属性是对象的情况
try {
    Object property = PropertyUtils.getNestedProperty(student, "friend.name");
    System.out.println(property); // 刘备
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

6、获取属性

// 12、获取属性
try {
    Object property = PropertyUtils.getProperty(student, "name");
    System.out.println(property); // 訾博
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

六、获取属性描述

1、获取属性描述 - 通过对象

// 13、获取属性描述 - 通过对象
try {
    PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(student, "name");
    System.out.println(propertyDescriptor);
    // 好强大呀!
    // java.beans.PropertyDescriptor[name=name; values={expert=false; visualUpdate=false; hidden=false;
    // enumerationValues=[Ljava.lang.Object;@204f30ec; required=false}; propertyType=class java.lang.String;
    // readMethod=public java.lang.String com.zibo.zibo2022.property_utils.entity.Student.getName();
    // writeMethod=public void com.zibo.zibo2022.property_utils.entity.Student.setName(java.lang.String)]
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

2、获取属性描述 - 通过类

// 14、获取属性描述 - 通过类
try {
    PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(Student.class, "name");
    System.out.println(propertyDescriptor);
    // java.beans.PropertyDescriptor[name=name; values={expert=false; visualUpdate=false; hidden=false;
    // enumerationValues=[Ljava.lang.Object;@527740a2; required=false}; propertyType=class java.lang.String;
    // readMethod=public java.lang.String java.lang.Class.getName()]
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

3、获取属性描述数组

// 15、获取属性描述数组
PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(student);
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
    System.out.println(propertyDescriptor); // 太多了,不写了
}

七、获取属性类型

1、获取已为此属性注册的任何显式 PropertyEditor Class

// 16、获取已为此属性注册的任何显式 PropertyEditor Class
try {
    Class<?> propertyEditorClass = PropertyUtils.getPropertyEditorClass(student, "name");
    System.out.println(propertyEditorClass); // 此处返回为 null ,具体不知道何用
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

2、获取属性类型

// 17、获取属性类型
try {
    Class<?> propertyType = PropertyUtils.getPropertyType(student, "name");
    System.out.println(propertyType); // class java.lang.String
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

八、判断属性可读可写

1、判断一个属性是否为可读属性

// 18、判断一个属性是否为可读属性
boolean isReadable = PropertyUtils.isReadable(student, "name");
System.out.println(isReadable); // true

2、判断一个属性是否为可写属性

// 19、判断一个属性是否为可写属性
boolean isWriteable = PropertyUtils.isWriteable(student, "name");
System.out.println(isWriteable); // true

九、设置属性值

1、设置指定索引属性值,适用于属性是list或者array的情况

// 20、设置指定索引属性值,适用于属性是list或者array的情况
try {
    PropertyUtils.setIndexedProperty(student, "hobbies[0]", "da篮球");
    System.out.println(student.getHobbies()); // [da篮球, 足球]
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

2、设置指定索引属性值,适用于属性是list或者array的情况

// 21、设置指定索引属性值,适用于属性是list或者array的情况
try {
    PropertyUtils.setIndexedProperty(student, "hobbies", 1, "足da球");
    System.out.println(student.getHobbies()); // [da篮球, 足da球]
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

3、设置指定属性值,适用于属性是 map 的情况

// 22、设置指定属性值,适用于属性是 map 的情况
try {
    PropertyUtils.setMappedProperty(student, "schoolMap(高中)", "某da高中");
    System.out.println(student.getSchoolMap()); // {大学=某大学, 高中=某da高中}
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

4、设置指定属性值,适用于属性是 map 的情况

// 23、设置指定属性值,适用于属性是 map 的情况
try {
    PropertyUtils.setMappedProperty(student, "schoolMap", "大学", "某da大学");
    System.out.println(student.getSchoolMap()); // {大学=某da大学, 高中=某da高中}
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

5、设置属性值

// 24、设置属性值
try {
    PropertyUtils.setProperty(student, "name", "某da学生");
    System.out.println(student.getName()); // 某da学生
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

6、设置简单属性值

// 25、设置属性值
try {
    PropertyUtils.setSimpleProperty(student, "name", "某da&da学生");
    System.out.println(student.getName()); // 某da学生
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new RuntimeException(e);
}

十、完整代码

package com.zibo.zibo2022.property_utils.main;

import com.zibo.zibo2022.property_utils.entity.Student;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.BeanIntrospector;
import org.apache.commons.beanutils.DefaultBeanIntrospector;
import org.apache.commons.beanutils.PropertyUtils;

/**
 * @author zibo
 * @date 2022/7/14 0014 18:41
 */
public class Main {

    public static void main(String[] args) {
        Map<String, String> schoolMap = new HashMap<>();
        schoolMap.put("高中", "某高中");
        schoolMap.put("大学", "某大学");
        Student student = new Student("訾博", 22, "北京", new Student.Friend("刘备", 26, "北京"), Arrays.asList("篮球", "足球"), schoolMap);

        // 看不懂,暂且搁置
        // 1、清空所有属性的描述信息
        // 说明:清除任何类加载器加载的所有类的任何缓存属性描述符信息。这在丢弃类加载器以实现类重新加载的情况下很有用。
        PropertyUtils.clearDescriptors();

        // 2、重置 BeanIntrospectors 的缓存属性描述符信息
        // 说明:将注册的 BeanIntrospector 对象重置为初始默认状态。
        PropertyUtils.resetBeanIntrospectors();

        // 3、添加一个 BeanIntrospector
        // 说明:添加一个 BeanIntrospector ,当需要获取类的属性描述符时调用该对象。
        PropertyUtils.addBeanIntrospector(DefaultBeanIntrospector.INSTANCE);

        // 4、移除一个 BeanIntrospector
        // 说明:移除指定的 BeanIntrospector 。
        BeanIntrospector instance = DefaultBeanIntrospector.INSTANCE;
        PropertyUtils.removeBeanIntrospector(instance);

        // 5、复制属性
        // 说明:经测试这是一种浅拷贝!
        try {
            Student student1 = new Student();
            // 参数:目标对象,源对象
            PropertyUtils.copyProperties(student1, student);
            System.out.println(student);
            // Student(name=訾博, age=22, address=北京, friend=Student.Friend(name=刘备, age=26, address=北京), hobbies=[篮球, 足球], schoolMap={大学=某大学, 高中=某高中})
            System.out.println(student1);
            // Student(name=訾博, age=22, address=北京, friend=Student.Friend(name=刘备, age=26, address=北京), hobbies=[篮球, 足球], schoolMap={大学=某大学, 高中=某高中})
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 6、获取属性描述
        // 说明:经测试发现,含所有属性和 class 属性
        try {
            Map<String, Object> map = PropertyUtils.describe(student);
            map.forEach((key, value) -> System.out.println(key + ":" + value));
            // address:北京
            // hobbies:[篮球, 足球]
            // friend:Student.Friend(name=刘备, age=26, address=北京)
            // name:訾博
            // schoolMap:{大学=某大学, 高中=某高中}
            // class:class com.zibo.zibo2022.property_utils.entity.Student
            // age:22
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 7、指定索引属性值,适用于属性是 list 或 array 的情况
        try {
            Object property = PropertyUtils.getIndexedProperty(student, "hobbies[0]");
            System.out.println(property); // 篮球
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 8、指定索引属性值,适用于属性是 list 或 array 的情况
        try {
            Object property = PropertyUtils.getIndexedProperty(student, "hobbies", 1);
            System.out.println(property); // 足球
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 9、获取 map 属性,适用于属性是 map 的情况
        try {
            Object property = PropertyUtils.getMappedProperty(student, "schoolMap(高中)");
            System.out.println(property); // 某高中
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 10、获取 map 属性,适用于属性是 map 的情况
        try {
            Object property = PropertyUtils.getMappedProperty(student, "schoolMap", "大学");
            System.out.println(property); // 某大学
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 11、获取嵌套属性,属性是对象的情况
        try {
            Object property = PropertyUtils.getNestedProperty(student, "friend.name");
            System.out.println(property); // 刘备
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 12、获取属性
        try {
            Object property = PropertyUtils.getProperty(student, "name");
            System.out.println(property); // 訾博
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 13、获取属性描述 - 通过对象
        try {
            PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(student, "name");
            System.out.println(propertyDescriptor);
            // 好强大呀!
            // java.beans.PropertyDescriptor[name=name; values={expert=false; visualUpdate=false; hidden=false;
            // enumerationValues=[Ljava.lang.Object;@204f30ec; required=false}; propertyType=class java.lang.String;
            // readMethod=public java.lang.String com.zibo.zibo2022.property_utils.entity.Student.getName();
            // writeMethod=public void com.zibo.zibo2022.property_utils.entity.Student.setName(java.lang.String)]
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 14、获取属性描述 - 通过类
        try {
            PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(Student.class, "name");
            System.out.println(propertyDescriptor);
            // java.beans.PropertyDescriptor[name=name; values={expert=false; visualUpdate=false; hidden=false;
            // enumerationValues=[Ljava.lang.Object;@527740a2; required=false}; propertyType=class java.lang.String;
            // readMethod=public java.lang.String java.lang.Class.getName()]
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 15、获取属性描述数组
        PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(student);
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            System.out.println(propertyDescriptor); // 太多了,不写了
        }

        // 16、获取已为此属性注册的任何显式 PropertyEditor Class
        try {
            Class<?> propertyEditorClass = PropertyUtils.getPropertyEditorClass(student, "name");
            System.out.println(propertyEditorClass); // 此处返回为 null ,具体不知道何用
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 17、获取属性类型
        try {
            Class<?> propertyType = PropertyUtils.getPropertyType(student, "name");
            System.out.println(propertyType); // class java.lang.String
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 18、判断一个属性是否为可读属性
        boolean isReadable = PropertyUtils.isReadable(student, "name");
        System.out.println(isReadable); // true

        // 19、判断一个属性是否为可写属性
        boolean isWriteable = PropertyUtils.isWriteable(student, "name");
        System.out.println(isWriteable); // true

        // 20、设置指定索引属性值,适用于属性是list或者array的情况
        try {
            PropertyUtils.setIndexedProperty(student, "hobbies[0]", "da篮球");
            System.out.println(student.getHobbies()); // [da篮球, 足球]
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 21、设置指定索引属性值,适用于属性是list或者array的情况
        try {
            PropertyUtils.setIndexedProperty(student, "hobbies", 1, "足da球");
            System.out.println(student.getHobbies()); // [da篮球, 足da球]
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 22、设置指定属性值,适用于属性是 map 的情况
        try {
            PropertyUtils.setMappedProperty(student, "schoolMap(高中)", "某da高中");
            System.out.println(student.getSchoolMap()); // {大学=某大学, 高中=某da高中}
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 23、设置指定属性值,适用于属性是 map 的情况
        try {
            PropertyUtils.setMappedProperty(student, "schoolMap", "大学", "某da大学");
            System.out.println(student.getSchoolMap()); // {大学=某da大学, 高中=某da高中}
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 24、设置属性值
        try {
            PropertyUtils.setProperty(student, "name", "某da学生");
            System.out.println(student.getName()); // 某da学生
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 25、设置属性值
        try {
            PropertyUtils.setSimpleProperty(student, "name", "某da&da学生");
            System.out.println(student.getName()); // 某da学生
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

    }

}

十一、常见错误

1、java.lang.NoSuchMethodException: Property ‘name’ has no getter method in class ‘class com.zibo.zibo2022.main.Tag’

答案:

用BeanUtils.getProperty获取属性的类必须是public,否则会报此错误!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值