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 ...
随机推荐
- [CodeForce]356D Bags and Coins
已知有n个包,和总共s个钱币. n,s<=70000. 每个包可以装钱币,还可以套别的包.每个包中的钱数等于 所有套的包的钱数 加上 自己装的钱. 所有的钱都在包内. 问给定每个包中的钱数,输出 ...
- iOS 高仿:花田小憩3.0.1
前言 断断续续的已经学习Swift一年多了, 从1.2到现在的2.2, 一直在语法之间徘徊, 学一段时间, 工作一忙, 再捡起来隔段时间又忘了.思来想去, 趁着这两个月加班不是特别多, 就决定用swi ...
- css考核点整理(十)-响应式开发经验,响应式页面的三种核心技术是什么
响应式开发经验,响应式页面的三种核心技术是什么
- cookingk配置项中的chunk:true含义
学习cooking,查看中文文档,发现有个配置chunk: true, 不明白具体含义,于是根据注释,找到了相关代码, 即chunk: true等同于以下代码: var webpackConfig = ...
- [iOS开发] 使用第三方字体不生效
iOS中使用第三方字体并不复杂,通常只需要如下三个步骤: 1. 将第三方字体文件添加到工程(Project)中: 2. 在info.plist中添加一个新的键"Fonts provided ...
- springmvc配置文件 spring-servlet
<?xml version="1.0" encoding="UTF-8"?><!-- Bean头部 --><beans xmlns ...
- codevs 1817 灾后重建
/* 暴力暴力 离线每次添边 堆优化dij 70 SPFA 80..... */ #include<iostream> #include<cstdio> #include< ...
- 数据库连接报错之IO异常(The Network Adapter could not establish the connection)
Io 异常: The Network Adapter could not establish the connection 有以下四个原因: 1.oracle配置 listener.ora 和tnsn ...
- async await的前世今生
async 和 await 出现在C# 5.0之后,给并行编程带来了不少的方便,特别是当在MVC中的Action也变成async之后,有点开始什么都是async的味道了.但是这也给我们编程埋下了一些隐 ...
- (JAVA)从零开始之--打印流PrintStream记录日志文件
这里的记录日志是利用打印流来实现的. 文本信息中的内容为String类型.而像文件中写入数据,我们经常用到的还有文件输出流对象FileOutputStream. File file = new Fil ...