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. 熟练掌握HDFS的Java API接口访问

    HDFS设计的主要目的是对海量数据进行存储,也就是说在其上能够存储很大量文件(可以存储TB级的文件).HDFS将这些文件分割之后,存储在不同的DataNode上, HDFS 提供了两种访问接口:She ...

  2. 9.28noip模拟试题

    1.栅栏迷宫 田野上搭建了一个黄金大神专用的栅栏围成的迷宫.幸运的是,在迷宫的边界上留出了两段栅栏作为迷宫的出口.更幸运的是,所建造的迷宫是一个“完美的”迷宫:即你能从迷宫中的任意一点找到一条走出迷宫 ...

  3. web 页面传值方法

    一. 使用QueryString变量    QueryString是一种非常简单也是使用比较多的一种传值方式,但是它将传递的值显示在浏览器的地址栏中,如果是传递一个或多个安全性要求不高或是结构简单的数 ...

  4. appium系列教程(转载)

    1.系列文章:转载来源:乙醇的cnblog http://www.kuqin.com/shuoit/20140704/340994.html 2.环境部署:http://www.51testing.c ...

  5. Nhibernate 智能提示 以及其他类库智能提示

    Nhibernate 的智能提示 Nhibernate.dll 放到以下路径 C:\Program Files (x86)\Reference Assemblies\Microsoft\Framewo ...

  6. JavaScript学习笔记之原型对象

    本文是学习<JavaScript高级程序设计>第六章的笔记. JS中,便于批量创建对象的三种模式: 1.工厂模式:用一个函数封装创建对象的细节,传入必要的参数,在函数内部new一个对象并返 ...

  7. 64位系统下System32文件系统重定向

    前言 因为一次偶然的机会,需要访问系统目录“C:/Windows/System32“文件夹下的内容,使用的测试机器上预装了win7 64系统.在程序运行中竟然发生了该文件路径不存在的问题!!通过查看网 ...

  8. TextView控件

    1.手动创建(不建议): TextView tv = new TextView(this); tv.setContent("你好"); setContentView(tv); 2. ...

  9. 未能解析目标框架“.NETFramework,Version=v4.0”的 mscorlib 错误的解决办法

    查看项目属性,发现该项目的目标框架是.NET Framework 4 Client Profile ,而被引用的程序集的目标框架是.NET Framework 4,将该项目的目标框架修改成.NET F ...

  10. 9张思维导图学习Javascript

    分别归类为: javascript变量 javascript运算符 javascript数组 javascript流程语句 javascript字符串函数 javascript函数基础 javascr ...