美文网首页
commons-beanutils的使用

commons-beanutils的使用

作者: tuacy | 来源:发表于2019-10-28 20:09 被阅读0次

       commons-beanutils是Apache提供的一个用于操作JAVA bean的工具包。里面提供了各种各样的工具类,让我们可以很方便的对bean对象的属性进行各种操作。

一 commons-beanutils依赖

       pom方式的引入(maven项目)。

        <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>

二 commons-beanutils的使用

       关于commons-beanutils的使用主要是熟悉commons-beanutils库里面MethodUtils、ConstructorUtils、PropertyUtils、BeanUtils、ConvertUtils的使用。

2.1 MethodUtils

       MethodUtils通过反射对对象的方法做各种各样的操作。

       MethodUtils提供的一些静态方法:

方法 返回值 解释
setCacheMethods(final boolean cacheMethods) void 设置是否缓存方法(缓存可以提高性能)
clearCache() int 清空方法缓存
invokeMethod(final Object object,final String methodName,final Object arg) Object 执行方法
invokeMethod(final Object object,final String methodName,Object[] args) Object 执行方法
invokeMethod(final Object object,final String methodName,Object[] args,Class<?>[] parameterTypes) Object 执行方法
invokeExactMethod(final Object object,final String methodName,final Object arg) Object 执行方法
invokeExactMethod(final Object object,final String methodName,Object[] args) Object 执行方法
invokeExactMethod(final Object object,final String methodName,Object[] args,Class<?>[] parameterTypes) Object 执行方法
invokeExactStaticMethod(final Object object,final String methodName,final Object arg) Object 执行静态方法
invokeExactStaticMethod(final Object object,final String methodName,Object[] args) Object 执行静态方法
invokeExactStaticMethod(final Object object,final String methodName,Object[] args,Class<?>[] parameterTypes) Object 执行静态方法
invokeStaticMethod(final Object object,final String methodName,final Object arg) Object 执行静态方法
invokeStaticMethod(final Object object,final String methodName,Object[] args) Object 执行静态方法
invokeStaticMethod(final Object object,final String methodName,Object[] args,Class<?>[] parameterTypes) Object 执行静态方法
getAccessibleMethod(final Class<?> clazz,final String methodName,final Class<?> parameterType) Method 返回一个可访问的方法
getAccessibleMethod(final Class<?> clazz,final String methodName,final Class<?>[] parameterTypes) Method 返回一个可访问的方法
getAccessibleMethod(final Method method) Method 返回一个可访问的方法
getAccessibleMethod(Class<?> clazz, Method method) Method 返回一个可访问的方法
getMatchingAccessibleMethod(final Class<?> clazz,final String methodName,final Class<?>[] parameterTypes) Method 查找与方法名及参数匹配的可访问方法
isAssignmentCompatible(final Class<?> parameterType, final Class<?> parameterization) boolean 确定是否可以使用一个类型作为方法调用参数
getPrimitiveWrapper(final Class<?> primitiveType) Class<?> 获得基本数据类型的包装类型
getPrimitiveType(final Class<?> wrapperType) Class<?> 获得包装类的基本数据类型
toNonPrimitiveClass(final Class<?> clazz) Class<?> 如果是简单数据类型则返回对应的包装类,否则返回本身

       因为MethodUtils里面的方法都比较简单,所以我们就不给出例子了。

2.2 ConstructorUtils

       ConstructorUtils通过反射对对象的构造方法做各种操作。

       ConstructorUtils提供的静态方法:

方法名 返回值 解释
invokeConstructor(final Class<T> klass, final Object arg) T 执行构造方法
invokeConstructor(final Class<T> klass, Object[] args) T 执行构造方法
invokeConstructor(final Class<T> klass,Object[] args,Class<?>[] parameterTypes) T 执行构造方法
invokeExactConstructor(final Class<T> klass, final Object arg) T 执行构造方法
invokeExactConstructor(final Class<T> klass, Object[] args) T 执行构造方法
invokeExactConstructor(final Class<T> klass,Object[] args,Class<?>[] parameterTypes) T 执行构造方法
getAccessibleConstructor(final Class<T> klass,final Class<?> parameterType) Constructor<T> 获得含有一个形参的构造方法
getAccessibleConstructor(final Class<T> klass,final Class<?>[] parameterTypes) Constructor<T> 获得含有指定类型形参的构造方法
getAccessibleConstructor(final Constructor<T> ctor) Constructor<T> 获得可访问构造方法

       因为ConstructorUtils里面的方法都比较简单,所以我们就不给出例子了。

2.3 PropertyUtils

       PropertyUtils通过反射对对象的属性做各种操作。

       PropertyUtils提供的静态方法:

方法 返回值 解释
clearDescriptors() void 清空所有属性描述信息
resetBeanIntrospectors() void 重置BeanIntrospector
addBeanIntrospector(final BeanIntrospector introspector) void 添加一个BeanIntrospector
removeBeanIntrospector(final BeanIntrospector introspector) boolean 移除BeanIntrospector
copyProperties(final Object dest, final Object orig) void 复制属性
describe(final Object bean) Map<String, Object> 属性描述,key属性名,value属性值
getIndexedProperty(final Object bean, final String name) Object 指定索引属性值,适用于属性是list或者array的情况
getIndexedProperty(final Object bean,final String name, final int index) Object 指定索引属性值,适用于属性是list或者array的情况
getMappedProperty(final Object bean, final String name) Object 获得Map属性,适用于属性是Map的情况
getMappedProperty(final Object bean,final String name, final String key) Object 获得Map属性中指定键对应的值,适用于属性是Map的情况
getNestedProperty(final Object bean, final String name) Object 获得嵌套属性,属性是对象的情况
getProperty(final Object bean, final String name) Object 获得属性
getPropertyDescriptor(final Object bean,final String name) PropertyDescriptor 获取属性描述
getPropertyDescriptors(final Class<?> beanClass) PropertyDescriptor[] 获得属性描述
getPropertyDescriptors(final Object bean) PropertyDescriptor[] 获得属性描述
getPropertyEditorClass(final Object bean, final String name) Class<?> 获得已为此属性注册的任何显式 PropertyEditor Class
getPropertyType(final Object bean, final String name) Class<?> 获得属性类型
getReadMethod(final PropertyDescriptor descriptor) Method 返回一个可访问的属性的getter方法
getSimpleProperty(final Object bean, final String name) Object 返回属性值
getWriteMethod(final PropertyDescriptor descriptor) Method 返回一个可访问的属性的setter方法
isReadable(final Object bean, final String name) boolean 判断是否为可读属性
isWriteable(final Object bean, final String name) boolean 判断是否为可写属性
setIndexedProperty(final Object bean, final String name,final Object value) void 设置指定索引属性值,适用于属性是list或者array的情况
setIndexedProperty(final Object bean, final String name, final int index, final Object value) void 设置指定索引属性值,适用于属性是list或者array的情况
setMappedProperty(final Object bean, final String name,final Object value) void 设置Map属性的值
setMappedProperty(final Object bean, final String name, final String key, final Object value) void 设置Map属性的值
setNestedProperty(final Object bean, final String name, final Object value) void 设置嵌套属性的值
setProperty(final Object bean, final String name, final Object value) void 设置属性值
setSimpleProperty(final Object bean, final String name, final Object value) void 设置属性值

       PropertyUtils的使用,如下实例。

public class PropertyUtilsTest {

    public static class Address {
        private String email;

        public Address(String email) {
            this.email = email;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }
    }

    public static class UserInfo {
        private String userName;
        private int age;
        private Address address;
        private List<String> friendsNames;
        private Map<String, String> tag;

        UserInfo(String userName, int age, Address address, List<String> friendsNames, Map<String, String> tag) {
            this.userName = userName;
            this.age = age;
            this.address = address;
            this.friendsNames = friendsNames;
            this.tag = tag;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public List<String> getFriendsNames() {
            return friendsNames;
        }

        public void setFriendsNames(List<String> friendsNames) {
            this.friendsNames = friendsNames;
        }

        public Map<String, String> getTag() {
            return tag;
        }

        public void setTag(Map<String, String> tag) {
            this.tag = tag;
        }

        public Address getAddress() {
            return address;
        }

        public void setAddress(Address address) {
            this.address = address;
        }
    }

    @Test
    public void test() {
        List<String> friendList = Lists.newArrayList("张三", "李四");
        Map<String, String> tag = Maps.newHashMap();
        tag.put("key1", "value1");
        tag.put("key2", "value2");
        UserInfo userInfo = new UserInfo("tuacy", 18, new Address("1@qq.com"), friendList, tag);
        try {
            Map<String, Object> propertyMap = PropertyUtils.describe(userInfo);
            Object friend0 = PropertyUtils.getIndexedProperty(userInfo, "friendsNames[0]"); // 张三
            Object friend0Temp = PropertyUtils.getIndexedProperty(userInfo, "friendsNames", 0); // 张三
            Object mapperProperty = PropertyUtils.getMappedProperty(userInfo, "tag(key1)"); // value1
            Object mapperPropertyTemp = PropertyUtils.getMappedProperty(userInfo, "tag", "key1"); // value1
            Object nestedProperty = PropertyUtils.getNestedProperty(userInfo, "address.email"); // 1@qq.com
            Object name = PropertyUtils.getProperty(userInfo, "userName"); // tuacy
            PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(userInfo, "userName"); // PropertyDescriptor是对属性的一个封装
            PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(userInfo); // 获取所有的属性
            Class<?> classType = PropertyUtils.getPropertyType(userInfo, "address"); // 获取属性的类型Address
            Method getMethod = PropertyUtils.getReadMethod(PropertyUtils.getPropertyDescriptor(userInfo, "userName")); // getUserName()方法
            Object simpleProperty = PropertyUtils.getSimpleProperty(userInfo, "userName");
            Method setMethod = PropertyUtils.getWriteMethod(PropertyUtils.getPropertyDescriptor(userInfo, "userName")); // setUserName()方法
            boolean isReadable = PropertyUtils.isReadable(userInfo, "userName"); // true
            boolean isWriteable = PropertyUtils.isWriteable(userInfo, "userName"); // true
            PropertyUtils.setIndexedProperty(userInfo, "friendsNames[0]", "张三第一次修改"); // 修改friendsNames第一个元素
            PropertyUtils.setIndexedProperty(userInfo, "friendsNames", 0, "张三第二次修改"); // 修改friendsNames第一个元素
            PropertyUtils.setMappedProperty(userInfo, "tag(key1)", "value1第一次修改"); // 修改tag key为key1的值
            PropertyUtils.setMappedProperty(userInfo, "tag", "key1", "value1第二次修改"); // 修改tag key为key1的值
            PropertyUtils.setNestedProperty(userInfo, "address.email", "1007@qq.com"); // 修改address属性对象对应的email属性
            PropertyUtils.setProperty(userInfo, "userName", "tuacy0"); // 修改userName对应的属性值
            PropertyUtils.setSimpleProperty(userInfo, "age", 19); // 修改age对应的属性值
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

2.4 BeanUtils

       BeanUtils通过反射提供了Bean对象的一些便捷操作方法。

       BeanUtils提供的静态方法:

方法名 返回值 解释
cloneBean(final Object bean) Object 克隆对象
copyProperties(final Object dest, final Object orig) void 复制属性
copyProperty(final Object bean, final String name, final Object value) void 复制属性,相当于设置属性
describe(final Object bean) Map<String, String> 描述
getArrayProperty(final Object bean, final String name) String[] 返回指定属性的值,作为字符串数组返回
getIndexedProperty(final Object bean, final String name) String 获取指定索引位置对象作为字符串返回
getIndexedProperty(final Object bean,final String name, final int index) String 获取指定索引位置对象作为字符串返回
getMappedProperty(final Object bean, final String name) String 获得Map属性值作为字符串返回
getMappedProperty(final Object bean, final String name, final String key) String 获得Map属性中指定键的值作为字符串返回
getNestedProperty(final Object bean, final String name) String 获得嵌套属性作为字符串返回
getProperty(final Object bean, final String name) String 获得属性值作为字符串返回
getSimpleProperty(final Object bean, final String name) String 获得属性值作为字符串返回
populate(final Object bean, final Map<String, ? extends Object> properties) void 将Map转换成对象
setProperty(final Object bean, final String name, final Object value) void 设置属性值
initCause(final Throwable throwable, final Throwable cause) boolean 对异常来进行包装的
createCache() Map<K, V> 创建缓存
getCacheFast(final Map<?, ?> map) boolean
setCacheFast(final Map<?, ?> map, final boolean fast) void

       BeanUtils的使用:

public class BeanUtilsTest {

    public static class Address {
        private String email;

        public Address(String email) {
            this.email = email;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }
    }

    public static class UserInfo {
        private String userName;
        private int age;
        private Address address;
        private List<String> friendsNames;
        private Map<String, String> tag;

        public UserInfo() {

        }

        public UserInfo(String userName, int age, Address address, List<String> friendsNames, Map<String, String> tag) {
            this.userName = userName;
            this.age = age;
            this.address = address;
            this.friendsNames = friendsNames;
            this.tag = tag;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public List<String> getFriendsNames() {
            return friendsNames;
        }

        public void setFriendsNames(List<String> friendsNames) {
            this.friendsNames = friendsNames;
        }

        public Map<String, String> getTag() {
            return tag;
        }

        public void setTag(Map<String, String> tag) {
            this.tag = tag;
        }

        public Address getAddress() {
            return address;
        }

        public void setAddress(Address address) {
            this.address = address;
        }
    }

    @Test
    public void test() {
        List<String> friendList = Lists.newArrayList("张三", "李四");
        Map<String, String> tag = Maps.newHashMap();
        tag.put("key1", "value1");
        tag.put("key2", "value2");
        UserInfo userInfo = new UserInfo("tuacy", 18, new Address("1@qq.com"), friendList, tag);
        try {
            Object voClone = BeanUtils.cloneBean(userInfo);
            UserInfo userInfo1 = new UserInfo();
            BeanUtils.copyProperties(userInfo1, userInfo);
            BeanUtils.copyProperty(userInfo1, "userName", "user1");
            Map<String, String> map = BeanUtils.describe(userInfo); // 获取所有的属性名字和属性对应的值,注意这里值都会转换成String
            String[] arrays =  BeanUtils.getArrayProperty(userInfo, "friendsNames"); // friendsNames数组转换成数组
            Object item = BeanUtils.getIndexedProperty(userInfo, "friendsNames[0]"); // 张三
            Object itemItem = BeanUtils.getIndexedProperty(userInfo, "friendsNames", 0); // 张三
            Object value = BeanUtils.getMappedProperty(userInfo, "tag(key1)"); // value1
            Object valueValue = BeanUtils.getMappedProperty(userInfo, "tag", "key1"); // value1
            Object email = BeanUtils.getNestedProperty(userInfo, "address.email"); // 1@qq.com
            String userName = BeanUtils.getProperty(userInfo, "userName"); // tuacy
            String userName0 = BeanUtils.getSimpleProperty(userInfo, "userName"); // tuacy
            UserInfo userInfo2 = new UserInfo();
            BeanUtils.populate(userInfo2, PropertyUtils.describe(userInfo)); // map转换成对象
            BeanUtils.setProperty(userInfo2, "userName", "tuacy0"); // map转换成对象
            NullPointerException nullPointerException = new NullPointerException("情况一");
            NullPointerException nullPointerException1 = new NullPointerException("情况二");
            BeanUtils.initCause(nullPointerException, nullPointerException1); // map转换成对象
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

2.5 ConvertUtils

       ConvertUtils提供了数据类型相互转换的一些方法。

       ConvertUtils静态方法介绍:

方法名 返回值 解释
convert(final Object value) String 将对象转换为字符串
convert(final String value, final Class<?> clazz) Object 将字符串转换为指定数据类型对象
convert(final String[] values, final Class<?> clazz) Object 将数组转换为指定数据类型对象
convert(final Object value, final Class<?> targetType) Object 将对象转换为指定数据类型对象
deregister() void 移除所有已经注册的转换器
deregister(final Class<?> clazz) void 移除指定类型的转换器
lookup(final Class<?> clazz) Converter 查找指定类型的转换器
lookup(final Class<?> sourceType, final Class<?> targetType) Converter 查找将指定类型转换为另一种类型的转换器
register(final Converter converter, final Class<?> clazz) void 注册转换器
primitiveToWrapper(final Class<T> type) Class<T> 基本类型转换成包装类

       ConvertUtils的使用。

public class ConvertUtilsTest {


    @Test
    public void test() {
        try {
            // 注册一个Date转换器,把字符串转换为Date
            ConvertUtils.register(new Converter() {
                @Override
                public <T> T convert(Class<T> type, Object value) {
                    try {
                        return (T) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) value);
                    } catch (ParseException e) {
                        return null;
                    }
                }
            }, Date.class);
            System.out.println(ConvertUtils.convert("2019-10-28 15:30:00", Date.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

相关文章

网友评论

      本文标题:commons-beanutils的使用

      本文链接:https://www.haomeiwen.com/subject/vlcivctx.html