org.springframework.beans.BeanUtils
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的更多相关文章
- org.springframework.beans.BeanUtils与org.apache.commons.beanutils.BeanUtils的copyProperties用法区别
知识点 org.springframework.beans.BeanUtils与org.apache.commons.beanutils.BeanUtils都提供了copyProperties方法,作 ...
- org.springframework.beans.BeanUtils的用法
s,t为对象BeanUtils.copyProperties(s, t); 将给定源bean的属性值复制到目标bean中 public static void copyProperties(Obje ...
- 解决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 ...
- org.springframework.beans.factory.BeanCreationException: 求教育!
2014-11-26 14:05:56 [org.springframework.web.context.support.XmlWebApplicationContext]-[WARN] Except ...
- 开发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 ...
- springtest mapper注入失败问题解决 {@org.springframework.beans.factory.annotation.Autowired(required=true)}
花费了一下午都没有搜索到相关解决方案的原因,一是我使用的 UnsatisfiedDependencyException 这个比较上层的异常(在最前面)来进行搜索, 范围太广导致没有搜索到,而且即便是有 ...
- springmvc上传文件报错org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.multipart.MultipartFile]
在用springmvc+mybatis进行项目开发时,上传文件抛异常... org.springframework.beans.BeanInstantiationException: Could no ...
- 【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 ...
- 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 ...
随机推荐
- android 44 SQLiteOpenHelper
java package com.sxt.day06_10; import java.util.ArrayList; import com.sxt.day06_10.entity.StudentBea ...
- winserve2008下不能运行winXP下开发的应用程序→更改“兼容性”
winserve2008下不能运行winXP下开发的应用程序 对策:更该“兼容性”
- [转] Understanding Twitter Bootstrap 3
Bootstrap is a popular, open source framework. Complete with pre-built components it allows web desi ...
- IE6与W3C标准的盒模型差异
盒子模型(Box Model)是 CSS 的核心,现代 Web 布局设计简单说就是一堆盒子的排列与嵌套,掌握了盒子模型与它们的摆放控制,会发现再复杂的页面也不过如此,然而,任何美好的事物都有缺憾,盒子 ...
- PHP编译安装出错configure: error: mcrypt.h not found. Please reinstall libmcrypt的解决办法
1.下载libmcrypt wget http://jaist.dl.sourceforge.net/project/mcrypt/Libmcrypt/2.5.8/libmcrypt-2.5.8.ta ...
- Junit简介和常用API
测试几个的概念 白盒测试——把测试对象看作一个打开的盒子,程序内部的逻辑结构和其他信息对测试人员是公开的. 回归测试——软件或环境的修复或更正后的“再测试”,自动测试工具对这类测试尤其有用. 单元测试 ...
- 学习微信小程序之css15解决父盒子高度塌陷
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- list-style无颜色问题解决,list-style-type无颜色解决
list-style无颜色问题解决,list-style-type无颜色解决 >>>>>>>>>>>>>>>& ...
- PL/SQL 触发器简介
与公司同事交流了一下,得知触发器很少用.性能是一方面,主要是如果用太多触发器,可能到时你都不知道会有什么操作自动发生. 有些操作可以在程序中控制.例如在插入某个表时,写个log表的记录.这可以用触发器 ...
- Android常用第三方框架
1.volley (截击) 项目地址 https://github.com/smanikandan14/Volley-demo (1) JSON,图像等的异步下载: (2) 网络请求的排序(sch ...