org.springframework.beans.BeanUtils的一个demo。可以很优雅的实现将父类字段的值copy到子类中

下面例子的输出结果(子类使用父类的toString方法,有点意思吧):
true
Person{name='people'}

import org.springframework.beans.BeanUtils;public class Test {public static void main(String[] args) {Person person = new Person("people");Male male = new Male();BeanUtils.copyProperties(person, male);System.out.println(Male.class.isInstance(male));System.out.println(male);}
}class Person {private String name;public Person() {}public Person(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +'}';}
}class Male extends Person {private String necklace;public Male() {}public Male(String name) {super(name);}public String getNecklace() {return necklace;}public void setNecklace(String necklace) {this.necklace = necklace;}
}

org.springframework.beans.BeanUtils
源码解析:
使用的是反射:

    /*** Copy the property values of the given source bean into the target bean.* <p>Note: The source and target classes do not have to match or even be derived* from each other, as long as the properties match. Any bean properties that the* source bean exposes but the target bean does not will silently be ignored.* <p>This is just a convenience method. For more complex transfer needs,* consider using a full BeanWrapper.* @param source the source bean* @param target the target bean* @throws BeansException if the copying failed* @see BeanWrapper*/public static void copyProperties(Object source, Object target) throws BeansException {copyProperties(source, target, null, (String[]) null);}

    /*** Copy the property values of the given source bean into the given target bean.* <p>Note: The source and target classes do not have to match or even be derived* from each other, as long as the properties match. Any bean properties that the* source bean exposes but the target bean does not will silently be ignored.* @param source the source bean* @param target the target bean* @param editable the class (or interface) to restrict property setting to* @param ignoreProperties array of property names to ignore* @throws BeansException if the copying failed* @see BeanWrapper*/private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties)throws BeansException {Assert.notNull(source, "Source must not be null");Assert.notNull(target, "Target must not be null");Class<?> actualEditable = target.getClass();if (editable != null) {if (!editable.isInstance(target)) {throw new IllegalArgumentException("Target class [" + target.getClass().getName() +"] not assignable to Editable class [" + editable.getName() + "]");} actualEditable = editable;//如果editable赋值,则ignore Target中的字段属性}PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);for (PropertyDescriptor targetPd : targetPds) {Method writeMethod = targetPd.getWriteMethod();if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());if (sourcePd != null) {Method readMethod = sourcePd.getReadMethod();if (readMethod != null &&ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {try {if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {readMethod.setAccessible(true);}Object value = readMethod.invoke(source);if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {writeMethod.setAccessible(true);}writeMethod.invoke(target, value);}catch (Throwable ex) {throw new FatalBeanException("Could not copy property '" + targetPd.getName() + "' from source to target", ex);}}}}}}

org.springframework.beans.BeanUtils相关推荐

  1. 使用org.springframework.beans.BeanUtils..copyProperties(sourse, target)方法复制属性

    使用org.springframework.beans.BeanUtils..copyProperties()方法进行copy两个类的属性. 注意: 1.源类Sourse中的属性需有get方法: 2. ...

  2. org.springframework.beans.factory.UnsatisfiedDependencyException

    严重: Context initialization failed org.springframework.beans.factory.UnsatisfiedDependencyException: ...

  3. SpringBoot启动报错:org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean

    SpringBoot启动报错:org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean ...

  4. 使用JPA进行update操作时,报org.springframework.beans.factory.BeanCreationException: Error creating bean with

    使用JPA进行update操作时,报org.springframework.beans.factory.BeanCreationException: Error creating bean with ...

  5. 报错 org.springframework.beans.factory.BeanCreationException

    2019独角兽企业重金招聘Python工程师标准>>> 一.问题背景: spring mvc eclipse启动报错:org.springframework.beans.factor ...

  6. org.springframework.beans.factory.BeanCreationException: Error creating bean with name

    严重: Exception sending context initialized event to listener instance of class org.springframework.we ...

  7. 解决 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type的问题...

    具体错误如下: Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying be ...

  8. 3org.springframework.beans.factory.BeanDefinitionStoreException异常

    3org.springframework.beans.factory.BeanDefinitionStoreException异常 参考文章: (1)3org.springframework.bean ...

  9. [解决方法] spring-data-mongo 配置报错org.springframework.beans.factory.BeanCreationException

    [解决方法] spring-data-mongo 配置报错org.springframework.beans.factory.BeanCreationException 参考文章: (1)[解决方法] ...

最新文章

  1. 儿科医生的眼泪,全被数据看见了
  2. swift的可选值(optional)
  3. html部分位置属性
  4. Linux _常用命令使用(一)
  5. ios项目中使用gcd的场景_Redis在PHP项目中的实际应用场景
  6. 自学python还是c4d_C4D到底需要学多久?要学到什么程度?
  7. Python中Queue.get()方法阻塞,怎么办?
  8. linux sed i参数,sed 慎用 -i 参数
  9. 软件设计师(中级)历年真题与知识点总结(更新中...)
  10. 谢晶:webpower中国区正在向“多渠道智能化营销”全面转型
  11. 图像处理之理解Homography matrix(单应性矩阵)
  12. 华东师范大学2019年数学分析考研试题
  13. 阿里云香港服务器被打流量攻击怎么办
  14. 期货反向跟单—恐惧来源于未知
  15. 如何在linux系统中设置定时任务?
  16. PIC16F877A与Proteus仿真-PIC16F877A最小系统及开发环境搭建
  17. 听了老同志的教导:\r \n 到底是什么
  18. java 多线程(三)
  19. QT软件开发: QProcess启动进程完成交互并获取输出
  20. python有限元传热求解_Python进行有限元编程-平面应力问题(三节点三角形单元)...

热门文章

  1. monkey基本命令及脚本编写
  2. Linux shell 字符串转数字进行运算符操作
  3. 《Windows 8 权威指南》——1.3 引入全新内核休眠模式,实现“瞬间开机”
  4. Android开源项目,圆形ImageView之CircleImageView
  5. UPNP解读2-含netbios,wins,DNS
  6. WCF之旅读书笔记(2):WCF如何通过Binding进行通信
  7. 为什么st2 chrome无法显示api中的例子
  8. 在GitHub上分享和展示你的代码
  9. row_number()over函数的使用(转)
  10. vim编辑器的快捷键使用