Apache Commons Beanutils 三 (BeanUtils、ConvertUtils、CollectionUtils...)

  • BeanUtils

简单介绍下两个方法的使用,populate和copyProperties,

populate可以帮助我们把Map里的键值对值拷贝到bean的属性值中;

copyProperties,顾名思义,帮我们拷贝一个bean的属性到另外一个bean中,注意是浅拷贝

如下示例:

package apache.commons.beanutils.example.utils;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import apache.commons.beanutils.example.pojo.User;


public class BeanUtilsTest
{

    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException
    {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "001");
        //map.put("address", "hz");
        map.put("id", "100");
        map.put("state", false);
        map.put("others", "others");
        
        
        User u = new User();
        BeanUtils.populate(u, map);
        
        System.out.println(u);
        
        
        User u1 = new User();
        BeanUtils.copyProperties(u1, u);
        System.out.println(u1);
    }
}

 

  • ConvertUtils

     

实际上,BeanUtils是依赖ConvertUtils来完成实际山的类型转换,但是有时候我们可能需要自定义转换器来完成特殊需求的类型转换;

自定义类型转换器步骤:

1、定义一个实现类实现Converter接口

2、调用ConvertUtils.register方法,注册该转换器

如下是一个实例,我们会在字符串转换的时候,加上一个前缀:

package apache.commons.beanutils.example.utils;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import apache.commons.beanutils.example.pojo.User;


public class CustomConverters
{

    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException
    {
        ConvertUtils.register(new StringConverter(), String.class);
        
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "001");
        map.put("address", "hz");
        map.put("id", "100");
        map.put("state", "false");
        
        
        User u = new User();
        BeanUtils.populate(u, map);
        
        System.out.println(u);
    }
}

class StringConverter implements Converter {  
    /**
     * 
     * 
     * @see org.apache.commons.beanutils.Converter#convert(java.lang.Class, java.lang.Object)
     * @param type
     * @param value
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public <T> T convert(Class<T> type, Object value)
    {

        if(String.class.isInstance(value)){
            return (T) ("###" + value);
        }else{
            return (T) value;
        }
        
    }  
}

这里有一点需要注意,像BeanUtilsConvertUtils 和 PropertyUtils工具类都是共享同一个转换器的,这样子虽然用起来很方便,但有时候显得不够灵活,实际上BeanUtilsConvertUtils 和 PropertyUtils都有一个对应的可实例化的类,即BeanUtilsBean、ConvertUtilsBean、PropertyUtilsBean;

它们的功能与BeanUtilsConvertUtils 和 PropertyUtils类似,区别是它们可以实例化,而且每个实例都可以拥有自己的类型转换器;

 

  • CollectionUtils

     

顾名思义,集合工具类,只不过它操作的都是集合里的bean,

利用这个工具类,我们可以批量修改、查询、过滤集合中的bean,甚至还可以拷贝集合中所有bean的某个属性到另外一个集合中,有点Java 8新特性 Streams 的感觉

如下示例:


package apache.commons.beanutils.example.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.beanutils.BeanPropertyValueChangeClosure;
import org.apache.commons.beanutils.BeanPropertyValueEqualsPredicate;
import org.apache.commons.beanutils.BeanToPropertyValueTransformer;
import org.apache.commons.collections.CollectionUtils;

import apache.commons.beanutils.example.pojo.User;



public class CollectionUtilsTest
{

    public static void main(String[] args)
    {
        List<User> userList = new ArrayList<User>();
        User u1 = new User();
        u1.setId(1l);
        u1.setName("chenpi1");
        u1.setState(true);
        User u2 = new User();
        u2.setId(2l);
        u2.setName("chenpi2");
        User u3 = new User();
        u2.setId(3l);
        u2.setName("chenpi3");
        u2.setState(true);
        userList.add(u1);
        userList.add(u2);
        userList.add(u3);

        //批量修改集合
        BeanPropertyValueChangeClosure closure = new BeanPropertyValueChangeClosure("name",
            "updateName");

        CollectionUtils.forAllDo(userList, closure);

        for (User tmp : userList)
        {
            System.out.println(tmp.getName());
        }
        
        BeanPropertyValueEqualsPredicate predicate =
            new BeanPropertyValueEqualsPredicate( "state", Boolean.TRUE );

        //过滤集合
        CollectionUtils.filter( userList, predicate );
        for (User tmp : userList)
        {
            System.out.println(tmp);
        }
        
        //创建transformer
        BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer( "id" );

        //将集合中所有你user的id传输到另外一个集合上
        Collection<?> idList = CollectionUtils.collect( userList, transformer );
        for (Object id : idList)
        {
            System.out.println(id);
        }
    }
}

 

 

 https://www.cnblogs.com/chenpi/p/6917499.html

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
BeanUtils.copyProperties是Apache Commons BeanUtils库中的一个方法,用于的值复制到另一个JavaBean对象中。它可以方便地实现对象之间的属性拷贝。 然而,BeanUtils.copyProperties()方法默认只会拷贝两个对象之间的同名属性,不会进行类型转换。对于内部类的属性,如果类型不匹配,拷贝操作可能会失败。 如果需要在拷贝过程中进行类型转换,可以使用ConvertUtils.register()方法注册自定义的类型转换器。例如,如果需要将内部类的属性从字符串类型转换为目标类型,可以注册一个自定义的类型转换器。 以下是一个示例代码,演示了如何使用BeanUtils.copyProperties()方法以及自定义类型转换器来拷贝包含内部类属性的对象: ```java // 导入相关类 import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.Converter; // 定义内部类 public class InnerClass { private String name; // getter和setter方法 } // 定义外部类 public class OuterClass { private InnerClass inner; // getter和setter方法 } // 自定义类型转换器 class InnerClassConverter implements Converter { @Override public <T> T convert(Class<T> type, Object value) { // 在这里进行类型转换逻辑的实现 // 将字符串转换为内部类对象 // 返回转换后的对象 return null; } } // 注册自定义类型转换器 ConvertUtils.register(new InnerClassConverter(), InnerClass.class); // 创建源对象和目标对象 OuterClass source = new OuterClass(); source.setInner(new InnerClass()); source.getInner().setName("example"); OuterClass target = new OuterClass(); // 使用BeanUtils.copyProperties()方法进行拷贝 BeanUtils.copyProperties(target, source); // 输出目标对象的属性值 System.out.println(target.getInner().getName()); ``` 请注意,上述示例中的自定义类型转换器InnerClassConverter需要根据实际需求进行实现,将字符串转换为内部类对象。在实际使用时,需要根据具体的业务逻辑进行相应的类型转换操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值