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;
} @Override
public 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与org.apache.commons.beanutils.BeanUtils的copyProperties用法区别

    知识点 org.springframework.beans.BeanUtils与org.apache.commons.beanutils.BeanUtils都提供了copyProperties方法,作 ...

  2. org.springframework.beans.BeanUtils的用法

    s,t为对象BeanUtils.copyProperties(s, t);  将给定源bean的属性值复制到目标bean中 public static void copyProperties(Obje ...

  3. 解决org.openqa.selenium.WebDriverException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms org.springframework.beans.BeanInstantiation

    解决方法为将selenium-server-standalone-2.37.0.jar升级至selenium-server-standalone-2.41.0.jar即可. 下载地址:http://s ...

  4. org.springframework.beans.factory.BeanCreationException: 求教育!

    2014-11-26 14:05:56 [org.springframework.web.context.support.XmlWebApplicationContext]-[WARN] Except ...

  5. 开发Spring过程中几个常见异常(二):Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'a' define

    本异常是小编在运行自己另外一篇博文中的例子时遇到的.(附博文:http://www.cnblogs.com/dudududu/p/8482487.html) 完整异常信息: 警告: Exception ...

  6. springtest mapper注入失败问题解决 {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    花费了一下午都没有搜索到相关解决方案的原因,一是我使用的 UnsatisfiedDependencyException 这个比较上层的异常(在最前面)来进行搜索, 范围太广导致没有搜索到,而且即便是有 ...

  7. springmvc上传文件报错org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.multipart.MultipartFile]

    在用springmvc+mybatis进行项目开发时,上传文件抛异常... org.springframework.beans.BeanInstantiationException: Could no ...

  8. 【spring mvc】后台spring mvc接收List参数报错如下:org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.util.List]: Specified class is an interface

    后台spring mvc接收List参数报错如下:org.springframework.beans.BeanInstantiationException: Failed to instantiate ...

  9. org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.hs.model.StudentModel]: No default constructor found; nested exception is java.lang.NoSuchMethodException: c

    root cause org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [c ...

随机推荐

  1. 1/8=1/a+1/b,a,b为自然数

    #include "stdio.h" int main(){ int a; int b; for(a=1;a<1000;a++)  {  for(b=1;b<1000; ...

  2. java解析xml文件四种方式

    1.介绍 1)DOM(JAXP Crimson解析器) DOM是用与平台和语言无关的方式表示XML文档的官方W3C标准.DOM是以层次结构组织的节点或信息片断的集合.这个层次结构允许开发人员在树中寻找 ...

  3. tcpdump 命令行抓包工具

    为了防止无良网站的爬虫抓取文章,特此标识,转载请注明文章出处.LaplaceDemon/SJQ. http://www.cnblogs.com/shijiaqi1066/p/3898248.html ...

  4. jQuery作用

    jquery是前端里面比较总要的,是很强大的一个选择器. 表单: 1.$(":input") 查找所有的input元素 2.$("text")    匹配所有的 ...

  5. Java-分页实例

    1.PageModel.java package com.javaweb; import java.util.List; public class PageModel<E> { priva ...

  6. 使用java注解的例子有没有

    使用java注解的例子 参考文档:http://www.cnblogs.com/pepcod/archive/2013/02/20/2918719.html http://www.shaoqun.co ...

  7. SQL语句之二建表

    use Test --进入需要建表的数据库if exists(select * from sysobjects where name='MyTable')--表是否已经存在drop table MyT ...

  8. iOS菜鸟之FMDB的二次封装简单易用

    闲来无事写点东西,希望大家多多指正! 大家先去git下载FMDB,然后将其中source文件夹中的fmdb文件夹拖入自己的项目中.最后就可以引用下面的代码对fmdb进行一次简单的封装. 这样可以更直观 ...

  9. Objective-C和C++的区别

    1.都是有C语言延伸而来2.OC是完全动态的,C++是部分动态的3.OC不支持多继承,通过代理 类别 协议优雅的实现了相关的一系列特性4.调用机制不同OC里面叫发送消息  C++叫做调用函数数5.OC ...

  10. C# 枚举

    一.在学习枚举之前,首先来听听枚举的优点. 1.枚举能够使代码更加清晰,它允许使用描述性的名称表示整数值. 2.枚举使代码更易于维护,有助于确保给变量指定合法的.期望的值. 3.枚举使代码更易输入. ...