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 ...
随机推荐
- Five ways to maximize Java NIO and NIO.2--reference
Java NIO -- the New Input/Output API package-- was introduced with J2SE 1.4 in 2002. Java NIO's purp ...
- GNU GRUB version 0.97 (630K lower /2053824K upper memory)
昨天把老板的IBM X61笔记本拿过来多系统,结果本以为很容易,直接ghost,结果悲剧发生啦,开机之后提示GNU GRUB version 0.97 (630K lower /2053824K up ...
- 基于GPUImage的实时美颜滤镜
1.背景 前段时间由于项目需求,做了一个基于GPUImage的实时美颜滤镜.现在各种各样的直播.视频App层出不穷,美颜滤镜的需求也越来越多.为了回馈开源,现在我把它放到了GitHub https:/ ...
- 1 加到 100 的 时间复杂度 C#.
//1 加到 100 的 时间复杂度: ; ; ; i <= n; i++){ sum += i; } T() = ; //Initialize 'n'. T() = ; //Initializ ...
- 利用html+ashx实现aspx的功能
最近准备学习下ASP.NET,初期在网上看了些视频教程,准备将自己学习的东西整理整理,留着日后可以参考参考. 本文采用了html.ashx实现aspx,实现了一个最简单的动态网页效果,开发环境是VS2 ...
- 开发自己的cordova插件
如果还没有配置过cordova环境,首先要下载nodejs,(下载地址https://nodejs.org/)下载完毕安装. 控制台: 1.输入npm -v 确定是否装上了 2.输入sudo npm ...
- iPhone中如何判断当前相机是否可用
UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; if (![UIImag ...
- Notification和KVO有什么不同
Notification是推送通知,我们可以建立一个通知中心,存放创建多个通知,在不同的地方在需要的时候push调用和KVO不同的是,KVO是键值观察,只能观察一个值,这就是区别
- .net版ckeditor配置水印功能(转)
本文简单讲解ckfinder控件给上图片加水印效果. 1.将ckfinder/plugins/watermark/bin/Debug目录下的CKFinder_Watermark.dll和CKFinde ...
- hdoj 2041 超级阶梯
代码: #include <stdio.h>int main(){int n;int i;int m;int count;int dp[50];while(scanf("%d&q ...