BeanUtils.copyProperties()的用法

BeanUtils.copyProperties()的用法
BeanUtils提供对Java反射和自省API的包装。

其主要目的是利用反射机制对JavaBean的属性进行处理。

我们知道,一个JavaBean通常包含了大量的属性,很多情况下,对JavaBean的处理导致大量get/set代码堆积,增加了代码长度和阅读代码的难度。

下面通过代码来理解BeanUtils首先创建两个类Person.java[java] view plaincopypackage ; import java.util.Date; public class Person { private String name; private String sex; private int age; private Date birthday; public String getName() { return name; }
public void setName(String name) { = name; } public String getSex()
{ return sex; } public void
setSex(String sex) { this.sex = sex; } public int getAge() { return age; }
public void setAge(int age) { this.age =
age; } public Date getBirthday()
{ return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } } Student.java[java] view
plaincopypackage ; import java.util.Date; public class Student { private String name;
private int age; private String address; private Date birthday; public String getName()
{ return name; } public void setName(String name) { =
name; } public int getAge() { return age; } public void setAge(int age)
{ this.age = age; } public String getAddress() { return address; }
public void setAddress(String address)
{ this.address = address; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday)
{ this.birthday =
birthday; } } 测试类BeanUtilTest.java[java] view plaincopypackage ; import ng.reflect.InvocationTargetException; import java.util.Date; //import
mons.beanutils.BeanUtils; import mons.beanutils.BeanUtils;
public class BeanUtilTest { public static void
main(String[] args) { Person per = new Person(); Student stu = new Student();
per.setName("zhangsan"); per.setSex("男"); per.setAge(20); per.setBirthday(new Date()); stu.setName("wuangwu"); stu.setAddress("北京市"); try
{ BeanUtils.copyProperties(stu,
per); } catch (IllegalAccessException e) { // TODO
Auto-generated catch block
e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block
e.printStackTrace(); }
System.out.println(stu.getName());
System.out.println(stu.getAge());
System.out.println(stu.getAddress());
System.out.println(stu.getBirthday()); } } 程序输出结果为:[plain] view plaincopyzhangsan 20 北京市Fri Nov 25 13:03:29 CST 2011 可见Student自己设置的值都被Person给覆盖了再做下面两个测试把Person中的setName和setAge 改为setname setage程
序输出结果为[plain] view plaincopyzhangsan 20 北京市Fri Nov 25 13:08:34 CST 2011 结果没有改变而如果改为setNAme, setAGe结果为:[plain] view plaincopywuangwu 0 北京市Fri Nov 25 13:10:25 CST 2011 我们发现结果改变了内容没有被覆盖注:当我们加载BeanUtils类时可能会报如下错误[java] view plaincopyException in thread "main" ng.ExceptionInInitializerError at .BeanUtilTest.main(BeanUtilTest.java:101) Caused by:
mons.logging.LogConfigurationE xception:
mons.logging.LogConfigurationE xception: ng.NullPointerException (Caused by ng.NullPointerException) (Caused by
mons.logging.LogConfigurationE xception: ng.NullPointerException (Caused by ng.NullPointerException)) at
mons.logging.impl.LogFactoryIm pl.newInstance(LogFactoryImpl.java:543) at
mons.logging.impl.LogFactoryIm pl.getInstance(LogFactoryImpl.java:235) at
mons.logging.impl.LogFactoryIm
pl.getInstance(LogFactoryImpl.java:209) at
mons.logging.LogFactory.getLog (LogFactory.java:351) at
mons.beanutils.BeanUtils.<clin it>(BeanUtils.java:111) ... 1 more Caused by: mons.logging.LogConfigurationE xception: ng.NullPointerException (Caused by ng.NullPointerException) at
mons.logging.impl.LogFactoryIm pl.getLogConstructor(LogFactoryImpl.java:397) at mons.logging.impl.LogFactoryIm pl.newInstance(LogFactoryImpl.java:529) ... 5 more Caused by: ng.NullPointerException at mons.logging.impl.LogFactoryIm pl.getLogConstructor(LogFactoryImpl.java:374) (6)
more 产生错误的原因是引入的包不对,应引入import mons.beanutils.BeanUtils;而不应是import mons.beanutils.BeanUtils;另外所需jar包为:
commons-beanutils-1.8.3.jarcommons-logging-1.1.1.jar还有一个很邪门的问题实在令我不解就是如果把Person,Student 测试类写在一起的话会产生问题类似与这样的结
构[java] view plaincopyclass Person{ ..... } class Student{ ..... } public class BeanUtilTest
{ public static void main(String[] args)
{ ...... } }。

合集下载

spring:beanutils.copyproperties将一个对象的数据塞入到另一个。。。

spring:beanutils.copyproperties将一个对象的数据塞入到另一个。。。

spring:beanutils.copyproperties将⼀个对象的数据塞⼊到另⼀个。

spring: beanutils.copyproperties将⼀个对象的数据塞⼊到另⼀个对象中(合并对象)它的出现原因: BeanUtils提供对Java反射和⾃省API的包装。

其主要⽬的是利⽤反射机制对JavaBean的属性进⾏处理。

我们知道,⼀个JavaBean通常包含了⼤量的属性,很多情况下,对JavaBean的处理导致⼤量get/set代码堆积,增加了代码长度和阅读代码的难度。

我有⼀个Category分类表对象,和⼀个ProductInfo商品表对象我需要的数据格式是(以分类作为基数,分类下⾯有多条帖⼦):data:[{"cid":1,"name":"灌⽔","theads":[{"id":1,"cid":1,"name":"有喜欢这歌的吗?""time":"2018-12-12 18:25"},{"id":1,"cid":1,"name":"有喜欢这歌的吗?""time":"2018-12-12 18:25"}]} ,{"cid":2,"name":"⽂学","theads":[{"id":18,"cid":2,"name":"徐志摩的诗""time":"2018-12-12 18:25"},{"id":21,"cid":2,"name":"鲁迅的散⽂""time":"2018-12-12 18:25"}]}]代码如下ResultVO resultVO = new ResultVO();//ProductVO productVO = new ProductVO();//List<ProductInfoVO> productInfoVOList = new ArrayList<ProductInfoVO>();//productVO.setProductInfoVOList(productInfoVOList);//resultVO.setData(productVO);//查询商品List<ProductInfo> productInfoList = product.findAll();//查询商品类⽬(⼀次性读完)//传统⽅法// List<Integer> categoryTypeList = new ArrayList<>();//for (ProductInfo productInfo: productInfoList)// {// categoryTypeList.add(productInfo.getCategoryType());//}//java8-lambda⽅法List<Integer> categoryTypeList = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());List<ProductCategory> CategoryList = category.findByCategoryTypeIn(categoryTypeList);//拼合数据for (ProductCategory category: CategoryList){//productCategoryProductVO productVO = new ProductVO();productVO.setCategoryType(category.getCategoryType());productVO.setCategoryName(category.getCategoryName());//productInfoList<ProductInfoVO> productInfoVOList = new ArrayList<>();for (ProductInfo productInfo : productInfoList){if(productInfo.getCategoryType().equals(category.getCategoryType())) {//⽼⽅法:ProductInfoVO productInfoVO = new ProductInfoVO();productInfoVO.setProductId(productInfo.getProductId());productInfoVO.setProductName(productInfo.getProductName()); productInfoVOList.add(productInfoVO);//新⽅法:将productInfo属性复制到productInfoVO1中//beanutils.copypropertiesProductInfoVO productInfoVO1 = new ProductInfoVO();BeanUtils.copyProperties(productInfo, productInfoVO1);productInfoVOList.add(productInfoVO1);}}productVO.setProductInfoVOList(productInfoVOList);}return resultVO;//return "list";。

java copyproperties方法

java copyproperties方法

java copyproperties方法在Java编程中,"copyProperties" 方法是一种常用的功能,它用于将一个对象中的属性值复制到另一个对象中。

这在对象之间的数据传递和对象转换时特别有用。

本文将详细解释Java中的copyProperties方法,并提供相应的使用示例。

### Java copyProperties 方法介绍`copyProperties` 方法通常在Java的BeanUtils或Spring的BeanWrapper中可以找到,其主要作用是在两个JavaBean之间复制属性。

它通过反射机制工作,可以自动识别并复制具有相同名称和兼容类型的属性。

在Spring框架中,`BeanWrapper` 接口提供了一个`copyProperties` 方法,而在Apache Commons的BeanUtils库中,也有一个同名的方法。

### 使用场景当你需要:- 在两个具有相似结构的对象间迁移数据。

- 在DTO(Data Transfer Object)和实体(Entity)之间转换数据。

- 创建对象的深拷贝。

### 示例以下是使用Spring的`BeanWrapper`和Apache Commons BeanUtils 库实现`copyProperties`的示例。

#### 使用Spring的BeanWrapper```javaimport org.springframework.beans.BeanWrapper;import org.springframework.beans.PropertyAccessorFactory;public class CopyPropertiesExample {public static void main(String[] args) {Source source = new Source();source.setName("John Doe");source.setAge(30);Destination destination = new Destination();BeanWrapper bwSource = PropertyAccessorFactory.forBeanPropertyAccess(source);BeanWrapper bwDestination = PropertyAccessorFactory.forBeanPropertyAccess(destination);bwDestination.copyProperties(bwSource);System.out.println(destination.getName()); // 输出:John DoeSystem.out.println(destination.getAge()); // 输出:30 }}class Source {private String name;private int age;// Getters and Setters}class Destination {private String name;private int age;// Getters and Setters}```#### 使用Apache Commons BeanUtils首先,需要添加BeanUtils的依赖。

BeanUtils.copyProperties在拷贝属性时忽略空值的操作

BeanUtils.copyProperties在拷贝属性时忽略空值的操作

BeanUtils.copyProperties在拷贝属性时忽略空值的操作BeanUtils.copyProperties忽略空值使⽤spring开发的⼈,对这⾏代码肯定不陌⽣,常⽤于DTO、VO、PO之间的复制。

/*** 全属性copy对象***/BeanUtils.copyProperties(Object source, Object target)但这⾏代码会将所有的属性都进⾏copy,有的时候我们想要个别属性不进⾏复制(⽐如:null值属性),这时就需要⽤到另⼀个⽅法:/*** 忽略某些属性copy对象***/BeanUtils.copyProperties(Object source, Object target, String... ignoreProperties)第三个参数是可变长类型,动态获取忽略的属性:/*** 获取需要忽略的属性** @param source* @return*/public static String[] getNullPropertyNames (Object source) {final BeanWrapper src = new BeanWrapperImpl(source);PropertyDescriptor[] pds = src.getPropertyDescriptors();Set<String> emptyNames = new HashSet<>();for(PropertyDescriptor pd : pds) {Object srcValue = src.getPropertyValue(pd.getName());// 此处判断可根据需求修改if (srcValue == null) {emptyNames.add(pd.getName());}}String[] result = new String[emptyNames.size()];return emptyNames.toArray(result);}拓展⼀下下:很多时候我们需要将Map与Bean之间转换,提供两种⽅式:⼀、使⽤fastjson1、map转bean:Map paramMap = new HashMap();String jsonStr = JSONObject.toJSONString(paramMap);Object infoDo = JSON.parseObject(jsonStr, Object.class);2、bean转map:Map<String, Object> map = JSON.parseObject(JSON.toJSONString(object),new TypeReference<Map<String,Object>>(){});⼆、使⽤commons-beanutils依赖包:<dependency><groupId>commons-beanutils</groupId><artifactId>commons-beanutils</artifactId><version>1.8.3</version></dependency>然后调⽤⽅法:/*** Bean转map** @param bean* @return*/public Map describe(Object bean);/*** map转bean** @param bean* @param map*/public void populate (Object bean, Map map);同时可以按指定的属性列表copy对象:/*** 按指定的属性列表赋值对象** @param source* @param target* @param properties**/public static void copyWithProperties(Object source, Object target, List<String> properties) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { for (String property : properties) {PropertyUtils.setProperty(target, property, PropertyUtils.getProperty(source, property));}}BeanUtils 在复制类时需要注意值为空的情况BeanUtils.copyProperties(dest, orig);此处引⽤的是 mons.beanutils.BeanUtils;ConvertUtils.register(new DateConverter(null), java.util.Date.class);添加这⼀⾏代码,解决date 类型为空报错ConvertUtils.register(new IntegerConverter(null), Integer.class);这⼀⾏,可以解决 integer值为空时不⾃动赋值为0;另外 double 可能也很特殊,我没研究。

hutool copyoptions使用

hutool copyoptions使用

Hutool是一套Java工具包,旨在简化Java开发中的常用操作。

其中,CopyOptions是用于配置对象复制选项的参数类。

以下是使用Hutool中的CopyOptions进行对象复制的一般步骤:导入Hutool的相关包:javaimport cn.hutool.core.util.ObjectUtil;import cn.hutool.core.util.StrUtil;import cn.hutool.core.bean.BeanUtil;创建要复制的对象:javaUser sourceUser = new User();sourceUser.setId(1);sourceUser.setName("John");sourceUser.setAge(25);创建目标对象:javaUser targetUser = new User();创建CopyOptions对象,并设置相关属性:javaCopyOptions copyOptions = new CopyOptions();copyOptions.setIgnoreNullValue(true); // 忽略值为null的属性copyOptions.setIgnoreError(true); // 忽略字段注入错误使用BeanUtil.copyProperties方法进行对象复制:javaBeanUtil.copyProperties(sourceUser, targetUser, copyOptions);在上述代码中,BeanUtil.copyProperties方法接收三个参数:源对象、目标对象和CopyOptions 对象。

该方法将根据CopyOptions中的配置选项,将源对象的属性复制到目标对象中。

6. 检查目标对象的属性是否正确复制:javaif (ObjectUtil.equal(sourceUser.getId(), targetUser.getId()) && sourceUser.getName().equals(targetUser.getName()) && sourceUser.getAge() == targetUser.getAge()) {System.out.println("复制成功!");} else {System.out.println("复制失败!");}上述代码将检查源对象的属性是否正确地复制到了目标对象中。

BeanUtils.copyProperties()拷贝id属性失败的原因及解决

BeanUtils.copyProperties()拷贝id属性失败的原因及解决

BeanUtils.copyProperties()拷贝id属性失败的原因及解决⽬录BeanUtils.copyProperties()拷贝id属性失败部分代码如下解决⽅法BeanUtils.copyProperties 出错BeanUtils.copyProperties()拷贝id属性失败po类中id有值,但是使⽤BeanUtils.copyProperties()拷贝出的vo类id属性为null,检查后发现是因为po继承的⽗类声明了⼀个泛型。

部分代码如下public abstract class AbstractEntity<ID extends Serializable> implements Serializable {protected ID id;/**创建⼈*/protected ID createdBy;/**创建时间*/protected Date createdTime;/**最后⼀次修改⼈*/protected ID lastModifiedBy;/**最后⼀次修改时间*/protected Date lastModifiedTime;public void setId(ID id) {this.id = id;}public ID getId() {return this.id;}查看BeanUtils.copyProperties()源码中有⼀段判断如下:if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType()))当执⾏到获取vo类的writeMethod即setId()参数类型,结果是Long类型,⽽po类的readMethod即getId()返回值类型获取到的结果却是Serializable所以BeanUtils认为属性类型不同,所以不会拷贝id属性。

hutool beancopy 方法

hutool beancopy 方法

hutool beancopy 方法
Hutool的BeanCopy方法可以帮助你复制JavaBean对象,其实现方式如下:
1. 创建一个新的Bean对象,其类型与源对象相同。

2. 使用BeanUtil的copyProperties方法,将源对象的属性值复制到新创建的对象中。

这个方法会遍历源对象的所有属性,并将它们的值复制到新对象中。

如果属性名和类型都相同,则可以直接复制;如果属性名相同但类型不同,则需要进行转换。

示例代码如下:
```java
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class BeanCopyApi {
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
Student stu = new Student(20, "zz", ()); // age=20, name=zz, date=T11:07:
("stu ==" + (stu));
Student1 stu1 = new Student1(); // key值相同,即复制,若类型不一致可能会导致转换错误
(stu, stu1);
("stu1==" + (stu1));
}
}
```。

java中beanutils copy引用类型

一、概述在Java编程中,我们经常需要将一个对象的属性值复制到另一个对象中。

BeanUtils是Apache Commons库中的一个工具类,它提供了一个方便的方法来完成这项任务。

在这篇文章中,我们将介绍BeanUtils的copy方法,重点讨论它在复制引用类型属性时的用法和注意事项。

二、BeanUtils的copy方法BeanUtils提供了一个copy方法,用于从一个对象复制属性到另一个对象。

该方法有多个重载形式,可以根据需要选择合适的重载版本来实现属性复制。

一般来说,copy方法可以完成基本类型和字符串类型属性的复制,但在复制引用类型属性时需要特殊处理。

三、复制引用类型属性1. 使用BeanUtils.copyProperty方法复制引用类型属性对于引用类型属性,我们不能简单地将源对象的引用赋给目标对象,因为这样会导致两个对象共享同一个引用,从而引起意外的属性修改。

为了解决这个问题,我们可以使用BeanUtils.copyProperty方法来复制引用类型属性。

```javaclass Source {private List<String> list;// getter and setter}class Target {private List<String> list;// getter and setter}Source source = new Source();source.setList(Arrays.asList("a", "b", "c"));Target target = new Target();BeanUtils.copyProperty(target, "list", newArrayList<>(source.getList()));// 现在target的list属性拥有了source的list属性的拷贝```2. 使用BeanUtils.copyProperties方法复制引用类型属性除了copyProperty方法,BeanUtils还提供了copyProperties方法,可以一次复制整个对象的属性。

JAVA重载copyProperties

JA V A重写copyProperties,使其支持Map类型农网门户开发中心高绪国最近,项目组要用到一个功能,就是用BeanUtils.copyProperties复制一个Map里的属性值到另外一个对象。

BeanUtils和PropertyUtils类是许多开源框架中频繁使用的两个工具,它们都能实现将一个类中的属性拷贝到另一个类中,这个功能甚至是spring实现依赖注入的基础。

研究一下apache的comon包中如何实现这个两个工具,可以发现它们都是使用ng.reflect和java.beans这两个包下的几个类来实现的。

但是BeanUtils.copyProperties只支持两个对象之间的复制,其原理:是利用反射读取到第一个对象(源类)的所有属性,然后对这些属性集合进行for循环,再在for循环里面判断这些属性是否有set方法,有则再对第二个对象(目标类)进行循环取出属性一一对比,相等则调用目标类的set方法得到源类的get方法得到的值。

改后主要就是两点:第一:源类(Map类型)的Key作为属性和目标类的属性对比,相等则取出此Key的Value赋给目标类(当然还是用目标类此属性的set方法)。

注意:如果是通过http请求的getParameterMap()得到的Map,其值是一个数组,一般只需要取第0项就可以了。

BeanUtils.copyProperties方法的源码限于篇幅,就不贴在此处了,有兴趣的可以百度一下或到我博客上去查看。

扩展后的copyProperties方法,这里为了表示和BeanUtils有“亲缘关系”,就新建了同名类并用同名方法,只是多做了一些处理,使其支持int/Integer、Date和自定义对象。

限于篇幅只贴了核心代码,详细的可以访问我的博客:/leadergg/archive/2008/12/11/3495586.aspx/**实现将源类(Map类型)属性拷贝到目标类中*@param Map map源Map对象*@param Object obj目标对象*@auther<a href="mailto:gaoxuguo@">Gao XuGuo</a>*2009-11-3013:11:29*/public static void copyProperties(Map map, Object obj) throws Exception {// 获取目标类的属性信息BeanInfo targetbean = Introspector.getBeanInfo(obj.getClass());PropertyDescriptor[] propertyDescriptors =targetbean.getPropertyDescriptors();// 对每个目标类的属性查找set方法,并进行处理for (int i = 0; i < propertyDescriptors.length; i++) {PropertyDescriptor pro = propertyDescriptors[i];Method wm = pro.getWriteMethod();if (wm != null) {Iterator ite = map.keySet().iterator();while (ite.hasNext()) {String key = (String) ite.next();// 判断匹配if(key.toLowerCase().equals(pro.getName().toLowerCase())) {if(!Modifier.isPublic(wm.getDeclaringClass().getModifiers())) {wm.setAccessible(true);}Object value = ((String[]) map.get(key))[0];String pt =splitSpace(pro.getPropertyType().getName());//判断类型是否匹配,不匹配则作强制转换if (!(pt.equals(value.getClass().getName()))) { value =parseByType(pro.getPropertyType(),value.toString());}// 调用目标类对应属性的set方法对该属性进行填充wm.invoke((Object) obj, new Object[] {value});break;}}}}}。

beanutils 用法

beanutils 用法Beanutils是一个开源的Java类库,提供了一组可以对JavaBean进行操作的工具类。

它可以简化JavaBean的属性赋值、属性拷贝和动态创建对象等操作。

本文将详细介绍beanutils的用法,包括属性赋值、属性拷贝、动态创建对象和处理集合等功能。

一、属性赋值属性赋值是beanutils的一个常见用法,它能够通过反射来设置JavaBean 的属性值。

下面是一个示例:User user = new User();BeanUtils.setProperty(user, "name", "John");在这个示例中,我们创建了一个User对象,并使用BeanUtils的setProperty方法来设置其属性值。

其中,第一个参数是要设置属性值的对象,第二个参数是要设置的属性名称,第三个参数是属性值。

除了使用setProperty方法,我们还可以使用copyProperties方法来实现属性赋值。

copyProperties方法可以将一个对象的属性值复制到另一个对象上,如下所示:User user1 = new User();User user2 = new User();user1.setName("John");BeanUtils.copyProperties(user2, user1);在这个示例中,我们创建了两个User对象,并将user1对象的属性值复制到user2对象上。

通过copyProperties方法,我们可以方便地实现对象属性的复制。

二、属性拷贝属性拷贝是beanutils的另一个重要功能,它可以将一个对象的属性值拷贝到另一个对象的相应属性上。

下面是一个示例:User user = new User();Map<String, Object> properties = new HashMap<>(); properties.put("name", "John");BeanUtils.populate(user, properties);在这个示例中,我们创建了一个User对象,并使用populate方法将Map 中的属性值拷贝到user对象上。

BeanUtils的使用

设a,b为对象BeanUtils.copyProperties(a, b);如果这里的BeanUtils是org.springframework.beans.BeanUtils,a拷贝到b。

如果BeanUtils是mons.beanutils.BeanUtils,b拷贝到a。

、BeanUtils.copyProperties 和populate的实现方法是将源bean(也可以是Map)中的每个element在转换器(Converter)的帮助下,将转换的结果设置到目标bean对应的属性中。

例如在HTTP应用中需要从http request中抽取数据,http request传递过来的都是String 或是String数组类型的变量而目标类型可能是各种各样的,例如http request会有一个name=visitDate,value='2009-05-13'的参数,而目标bean 的visitDate属性的类型是java.util.Date。

BeanUtils的copyProperties和populate需要在转换器(converter)的配合下实现源和目标对象之间的数据类型的转换。

在BeanUtils.copyProperties的javadoc中说明的(Copy property values from the origin bean to the destination bean for all cases where the property names are the same——只要属性名相同就可以从源bean中拷贝值到目标bean 中)这句话提供到功能就是要通过转换器才能实现的。

在BeanUtils的copyProperties和populate的使用过程中Converter是一个非常重要的概念,它提供了强大的扩展能力。

/****************************************************************/ public interface Converter {public Object convert(Class type, Object value);}/*********************************************************** *****/convert方法的参数type是目标转换的类型,参数value是被转换的值,返回值就是转换以后的结果。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
相关文档
最新文档