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);
                        }
                    }
                }
            }
        }
    }
时间: 2024-10-24 15:15:45

org.springframework.beans.BeanUtils的相关文章

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

2014-11-26 14:05:56 [org.springframework.web.context.support.XmlWebApplicationContext]-[WARN] Exception encountered during context initialization - cancelling refresh attemptorg.springframework.beans.factory.BeanCreationException: Error creating bean

【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 [java.util.List]: Specified class is an interface org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.util.List]: Speci

springsecurity启动出现org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: You must use a 3.0 schema with Spring Security 3.0.

在换了spring-security的jar包以后启动出现org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: You must use a 3.0 schema with Spring Security 3.0.Please update your schema declarations to the 3.0.3 schema (spring-securi

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named &#39;App&#39; is defined

工具:Eclipse mars 环境:jdk1.8 说明:这是在学习Spring Task时遇到的一个bug,代码如下: 定时任务类: package com.task.test; import java.util.Date; import org.springframework.stereotype.Component; @Component public class App { public void execute1(){ System.out.printf("Task: %s, Curr

异常:Struts:org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find BasicDataSource

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.apache.commons.dbcp.BasicDataSource] for bean with name 'dataSource' defined in class path resource [beans.xml]; nested exception is java.lang.ClassNotFoundExcepti

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException:

严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListenerorg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'daoSupport': Injection of resou

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException

1.错误描写叙述 usage: java org.apache.catalina.startup.Catalina [ -config {pathname} ] [ -nonaming ] { -help | start | stop } 2014-7-13 18:02:58 org.apache.catalina.core.AprLifecycleListener init 信息: Loaded APR based Apache Tomcat Native library 1.1.29 usi

?--Porg.springframework.beans.MethodInvocationException: Property &#39;username&#39; threw exception; nested exception is java.lang.NullPointerException

使用BoneCP作为连接池,在启动Tomcat报出以下异常: 一月 02, 2016 2:12:17 下午 org.apache.tomcat.util.digester.SetPropertiesRule begin警告: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:mynewdpi' did not find a

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [/Users/lonecloud/tomcat/apache-tomcat-7.0.70 2/webapps/myproject/WEB-INF/classes/cn/lone

解决这个报错的解决办法: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [/Users/lonecloud/tomcat/apache-tomcat-7.0.70 2/webapps/myproject/WEB-INF/classes/cn/lonecloud/dao/Impl/UserDaoImpl.class]; ne