com.sunchenbin.store.feilong.core.bean.BeanUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.sunchenbin.store.feilong.core.bean.BeanUtil.java

Source

/*
 * Copyright (C) 2008 feilong
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sunchenbin.store.feilong.core.bean;

import java.beans.PropertyDescriptor;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sunchenbin.store.feilong.core.util.Validator;

/**
 * ? org.apache.commons.beanutils?.
 * 
 * <h3>?:</h3>
 * 
 * <blockquote>
 * <p>
 * ??, {@link org.apache.commons.beanutils.ConvertUtilsBean#register(boolean, boolean, int) ConvertUtilsBean.register(boolean,
 * boolean, int)}<br>
 * ??,beanUtils,????<br>
 * ?,,? {@link org.apache.commons.beanutils.Converter},<br>
 *    ??:
 * </p>
 * 
 * <ul>
 * <li>{@link ConvertUtilsBean#registerPrimitives(boolean) registerPrimitives(boolean throwException)}</li>
 * <li>{@link ConvertUtilsBean#registerStandard(boolean,boolean) registerStandard(boolean throwException, boolean defaultNull);}</li>
 * <li>{@link ConvertUtilsBean#registerOther(boolean) registerOther(boolean throwException);}</li>
 * <li>{@link ConvertUtilsBean#registerArrays(boolean,int) registerArrays(boolean throwException, int defaultArraySize);}</li>
 * </ul>
 * 
 *  register,{@link org.apache.commons.beanutils.ConvertUtilsBean#deregister(Class) ConvertUtilsBean.deregister(Class)}
 * 
 * <p>
 * Example 1:
 * </p>
 * 
 * <pre>
 * 
 * MyObject myObject = new MyObject();
 * myObject.setId(3l);
 * myObject.setName(&quot;My Name&quot;);
 * 
 * ConvertUtilsBean cub = new ConvertUtilsBean();
 * cub.deregister(Long.class);
 * cub.register(new MyLongConverter(), Long.class);
 * 
 * LOGGER.debug(cub.lookup(Long.class));
 * 
 * BeanUtilsBean bub = new BeanUtilsBean(cub, new PropertyUtilsBean());
 * 
 * LOGGER.debug(bub.getProperty(myObject, &quot;name&quot;));
 * LOGGER.debug(bub.getProperty(myObject, &quot;id&quot;));
 * </pre>
 * 
 * </blockquote>
 * 
 * 
 * <h3>{@link PropertyUtils} {@link BeanUtils}:</h3>
 * 
 * <blockquote>
 * 
 * <pre>
 * BeanUtils.setProperty(pt1, &quot;x&quot;, &quot;9&quot;); // 9String
 * PropertyUtils.setProperty(pt1, &quot;x&quot;, 9); // int
 * // BeanUtilsPropertyUtils,?int,??
 * </pre>
 * 
 * <p>
 * {@link PropertyUtils} {@link BeanUtils}??,??<br>
 * BeanUtils??"Bean",String,<br>
 * PropertyUtils??,Object
 * </p>
 * </blockquote>
 * 
 * <h3> {@link BeanUtils#copyProperty(Object, String, Object) copyProperty}  {@link BeanUtils#setProperty(Object, String, Object)
 * setProperty}:</h3>
 * 
 * <blockquote>
 * 
 * <pre>
 * 
 * 
 * :
 * copyProperty ??bean,?beansetter
 * copyProperty ??beanMap,?beanMapsetter
 * 
 * 
 * ?bean?,{@link BeanUtils#copyProperty(Object, String, Object)}?;
 * {@link BeanUtils#setProperty(Object, String, Object)}  {@link BeanUtils#populate(Object,Map)},?populate(),?override {@link BeanUtils#setProperty(Object, String, Object)}.
 * ,?,{@link BeanUtils#setProperty(Object, String, Object)}???.
 * </pre>
 * 
 * </blockquote>
 * 
 * 
 * <h3>propertyName:</h3>
 * 
 * <blockquote>
 * 
 * <pre>
 * {@code
 * getPropertysetProperty,?2?,JavaBean,????.
 * Company c = new Company();
 * c.setName("Simple");
 * 
 * Simple,?????
 * //Simple
 * LOGGER.debug(BeanUtils.getProperty(c, "name"));
 * 
 * Map,???key??
 * //Map
 *     LOGGER.debug(BeanUtils.getProperty(c, "address (A2)"));
 *     HashMap am = new HashMap();
 *     am.put("1","234-222-1222211");
 *     am.put("2","021-086-1232323");
 *     BeanUtils.setProperty(c,"telephone",am);
 * LOGGER.debug(BeanUtils.getProperty(c, "telephone (2)"));
 * 
 * Indexed,??[]?,?ArrayList???.
 * //index
 *     LOGGER.debug(BeanUtils.getProperty(c, "otherInfo[2]"));
 *     BeanUtils.setProperty(c, "product[1]", "NOTES SERVER");
 *     LOGGER.debug(BeanUtils.getProperty(c, "product[1]"));
 * 
 * 3????
 * //nest
 *     LOGGER.debug(BeanUtils.getProperty(c, "employee[1].name"));
 * }
 * </pre>
 * 
 * </blockquote>
 * 
 * @author feilong
 * @version 1.0.0 2010-7-9 ?02:44:36
 * @version 1.0.2 2012-5-15 15:07
 * @version 1.0.7 2014521 ?12:24:53 move to om.feilong.commons.core.bean package
 * @version 1.0.8 2014-7-22 12:37 ? BeanUtilException 
 * 
 * @see com.sunchenbin.store.feilong.core.bean.PropertyUtil
 * 
 * @see java.beans.BeanInfo
 * @see java.beans.PropertyDescriptor
 * @see java.beans.MethodDescriptor
 * 
 * @see org.apache.commons.beanutils.BeanUtils
 * @see org.apache.commons.beanutils.Converter
 * @see org.apache.commons.beanutils.converters.DateConverter
 * @see org.apache.commons.beanutils.converters.DateTimeConverter
 * @see org.apache.commons.beanutils.converters.AbstractConverter
 * 
 * @see org.apache.commons.beanutils.ConvertUtils#register(org.apache.commons.beanutils.Converter, Class)
 * 
 * @see org.apache.commons.beanutils.ConvertUtilsBean#registerPrimitives(boolean)
 * @see org.apache.commons.beanutils.ConvertUtilsBean#registerStandard(boolean, boolean)
 * @see org.apache.commons.beanutils.ConvertUtilsBean#registerOther(boolean)
 * @see org.apache.commons.beanutils.ConvertUtilsBean#registerArrays(boolean, int)
 * 
 * @see "org.springframework.beans.BeanUtils"
 * 
 * @since 1.0.0
 */
public final class BeanUtil {

    /** The Constant LOGGER. */
    private static final Logger LOGGER = LoggerFactory.getLogger(BeanUtil.class);

    /** Don't let anyone instantiate this class. */
    private BeanUtil() {
        //AssertionError?. ?????. ???.
        //see Effective Java 2nd
        throw new AssertionError("No " + getClass().getName() + " instances for you!");
    }

    static {
        boolean throwException = false;
        boolean defaultNull = true;
        int defaultArraySize = 10;

        //XXX 
        BeanUtilsBean beanUtilsBean = BeanUtilsBean.getInstance();
        ConvertUtilsBean convertUtils = beanUtilsBean.getConvertUtils();

        convertUtils.register(throwException, defaultNull, defaultArraySize);
    }

    // [start] copyProperties

    /**
     * ? {@code fromObj-->toObj}.
     * 
     * <h3>?:</h3> <blockquote>
     * <ol>
     * <li>?copy?,??2Bean???ref, ??, .</li>
     * <li> {@link BeanUtils#copyProperties(Object, Object)} ,Object--->String--->Object?,<br>
     * ?copy?,, {@link PropertyUtil#copyProperties(Object, Object, String...)}</li>
     * </ol>
     * </blockquote>
     * 
     * 
     * <h3>?:</h3>
     * 
     * <blockquote>
     * 
     * <ol>
     * <li>includePropertyNames,? <code>fromObj</code>??,</li>
     * <li>includePropertyNames,? <code>fromObj</code>, <code>toObj</code>??,??,see
     * {@link org.apache.commons.beanutils.BeanUtilsBean#copyProperty(Object, String, Object)} Line391</li>
     * <li>
     * 
     * <p>
     *  {@link java.util.Date}  ?copy, ??:
     * </p>
     * 
     * <p>
     * DateConverter converter = new DateConverter(DatePattern.forToString, Locale.US);<br>
     * ConvertUtils.register(converter, Date.class);
     * </p>
     * 
     * :
     * <p>
     * ConvertUtils.register(new DateLocaleConverter(Locale.US, DatePattern.forToString), Date.class); <br>
     * BeanUtil.copyProperty(b, a, &quot;date&quot;);
     * </p>
     * 
     * </li>
     * </ol>
     * </blockquote>
     * 
     * 
     * <h3>:</h3>
     * 
     * <blockquote>
     * 
     * <pre>
     * pojo:enterpriseSalesenterpriseSales_form ?&quot;enterpriseName&quot;,&quot;linkMan&quot;,&quot;phone&quot;
     * 
     * 
     * enterpriseSales.setEnterpriseName(enterpriseSales_form.getEnterpriseName());
     * enterpriseSales.setLinkMan(enterpriseSales_form.getLinkMan());
     * enterpriseSales.setPhone(enterpriseSales_form.getPhone());
     * 
     * ,?
     * BeanUtil.copyProperties(enterpriseSales,enterpriseSales_form,new String[]{&quot;enterpriseName&quot;,&quot;linkMan&quot;,&quot;phone&quot;});
     * </pre>
     * 
     * </blockquote>
     * 
     * 
     * <h3>{@link BeanUtils#copyProperties(Object, Object)} {@link PropertyUtils#copyProperties(Object, Object)}</h3>
     * 
     * <blockquote>
     * <ul>
     * <li>{@link BeanUtils#copyProperties(Object, Object)}??????,????</li>
     * <li>{@link PropertyUtils#copyProperties(Object, Object)} ???,??JavaBean?????,???,???,.</li>
     * <li>commons-beanutils v1.9.0? BeanUtils?? null,PropertyUtils?? null.<br>
     * (<b>:</b>commons-beanutils v1.9.0+?,BeanUtilsBean.copyProperties() no longer throws a ConversionException for null properties
     * of certain data types),?,??commons-beanutils
     * {@link <a href="http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/RELEASE-NOTES.txt">RELEASE-NOTES.txt</a>}</li>
     * </ul>
     * </blockquote>
     *
     * @param toObj
     *            
     * @param fromObj
     *            
     * @param includePropertyNames
     *            ???,(can be nested/indexed/mapped/combo)<br>
     *             null or empty , {@link BeanUtils#copyProperties(Object, Object)}
     * @see #setProperty(Object, String, Object)
     * @see org.apache.commons.beanutils.BeanUtilsBean#copyProperties(Object, Object)
     * @see <a href="http://www.cnblogs.com/kaka/archive/2013/03/06/2945514.html">Bean??(Apache BeanUtils?PropertyUtils,Spring
     *      BeanUtils,Cglib BeanCopier)</a>
     */
    //XXX add excludePropertyNames support
    public static void copyProperties(Object toObj, Object fromObj, String... includePropertyNames) {
        if (null == toObj) {
            throw new NullPointerException("No destination bean/toObj specified");
        }
        if (null == fromObj) {
            throw new NullPointerException("No origin bean/fromObj specified");
        }

        if (Validator.isNullOrEmpty(includePropertyNames)) {
            try {
                BeanUtils.copyProperties(toObj, fromObj);
                return;
            } catch (Exception e) {
                LOGGER.error(e.getClass().getName(), e);
                throw new BeanUtilException(e);
            }
        }
        for (String propertyName : includePropertyNames) {
            String value = getProperty(fromObj, propertyName);
            setProperty(toObj, propertyName, value);
        }
    }

    // [end]

    // [start] setProperty

    /**
     *  {@link BeanUtils#setProperty(Object, String, Object)} ?(<b>?</b>).
     * 
     * @param bean
     *            Bean on which setting is to be performed
     * @param propertyName
     *            Property name (can be nested/indexed/mapped/combo)
     * @param value
     *            Value to be set
     * @see org.apache.commons.beanutils.BeanUtils#setProperty(Object, String, Object)
     * 
     * @see org.apache.commons.beanutils.BeanUtilsBean#setProperty(Object, String, Object)
     * 
     * @see org.apache.commons.beanutils.PropertyUtils#setProperty(Object, String, Object)
     * @see com.sunchenbin.store.feilong.core.bean.PropertyUtil#setProperty(Object, String, Object)
     */
    public static void setProperty(Object bean, String propertyName, Object value) {
        try {
            // BeanUtils??,???(?)
            BeanUtils.setProperty(bean, propertyName, value);
        } catch (Exception e) {
            LOGGER.error(e.getClass().getName(), e);
            throw new BeanUtilException(e);
        }
    }

    // [end]

    // [start] getProperty

    /**
     *  {@link BeanUtils#getProperty(Object, String)} ?.
     *
     * @param bean
     *            bean
     * @param propertyName
     *            ??
     * @return BeanUtils?
     * @see org.apache.commons.beanutils.BeanUtils#getProperty(Object, String)
     * @see org.apache.commons.beanutils.PropertyUtils#getProperty(Object, String)
     * @see com.sunchenbin.store.feilong.core.bean.PropertyUtil#getProperty(Object, String)
     */
    public static String getProperty(Object bean, String propertyName) {
        // Return the value of the specified property of the specified bean,
        // no matter which property reference format is used, as a String.
        try {
            return org.apache.commons.beanutils.BeanUtils.getProperty(bean, propertyName);
        } catch (Exception e) {
            LOGGER.error(e.getClass().getName(), e);
            throw new BeanUtilException(e);
        }
    }

    // [end]

    // [start] cloneBean

    /**
     * {@link BeanUtils#cloneBean(Object)}.
     * 
     * <p>
     * bean,???bean
     * <p>
     * 
     * <p>
     * {@link BeanUtils#cloneBean(Object)}??getPropertyUtils().copyProperties(newBean, bean);<br>
     * ?<b>? ,clone</b>
     * </p>
     * 
     * <p>
     * ???,????,?clone,,?,<br>
     * clone
     * </p>
     *
     * @param <T>
     *            the generic type
     * @param bean
     *            Bean to be cloned
     * @return the cloned bean
     *         (? ,clone)
     * @see org.apache.commons.beanutils.BeanUtils#cloneBean(Object)
     * @see org.apache.commons.beanutils.PropertyUtilsBean#copyProperties(Object, Object)
     */
    @SuppressWarnings("unchecked")
    public static <T> T cloneBean(T bean) {
        try {
            //Clone a bean based on the available property getters and setters, even if the bean class itself does not implement Cloneable.
            return (T) BeanUtils.cloneBean(bean);
        } catch (Exception e) {
            LOGGER.error(e.getClass().getName(), e);
            throw new BeanUtilException(e);
        }
    }

    // [end]

    // [start] describe BeanMap?

    /**
     * <code>bean</code>?(read method),??/Map.
     * 
     * <p>
     * ???class,Object??,classjava.lang.Object.
     * </p>
     * <p>
     * <span style="color:red">:<br>
     * ConvertUtils.register(dateTimeConverter, java.util.Date.class)?</span><br>
     * 
     * , {@link BeanUtilsBean#getNestedProperty(Object, String)},  ConvertUtilsBean?? <br>
     *  {@link ConvertUtilsBean#ConvertUtilsBean()}  ?
     * </p>
     *
     * @param bean
     *            Bean whose properties are to be extracted
     * @return Map of property descriptors
     * @see org.apache.commons.beanutils.BeanUtils#describe(Object)
     * @see org.apache.commons.beanutils.PropertyUtils#describe(Object)
     * @see PropertyUtil#describe(Object)
     * @see PropertyDescriptor
     * @see #populate(Object, Map)
     */
    public static Map<String, String> describe(Object bean) {
        try {
            //Return the entire set of properties for which the specified bean provides a read method.
            return BeanUtils.describe(bean);
        } catch (Exception e) {
            LOGGER.error(e.getClass().getName(), e);
            throw new BeanUtilException(e);
        }
    }

    // [end]

    // [start] populate() properties/map?bean

    /**
     * properties/map?populate() bean.
     *
     * @param bean
     *            JavaBean whose properties are being populated
     * @param properties
     *            Map keyed by property name,with the corresponding (String or String[]) value(s) to be set
     * @see org.apache.commons.beanutils.BeanUtils#populate(Object, Map)
     */
    public static void populate(Object bean, Map<String, ?> properties) {
        try {
            BeanUtils.populate(bean, properties);
        } catch (Exception e) {
            LOGGER.error(e.getClass().getName(), e);
            throw new BeanUtilException(e);
        }
    }

    // [end]
}