com.feilong.commons.core.bean.BeanUtil.java Source code

Java tutorial

Introduction

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

Source

/*
 * Copyright (C) 2008 feilong (venusdrogon@163.com)
 *
 * 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.feilong.commons.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.feilong.commons.core.util.Validator;

/**
 * ? org.apache.commons.beanutils?.
 * 
 * 
 * <h3>?:</h3>
 * 
 * <blockquote>
 * <p>
 * ??, {@link org.apache.commons.beanutils.ConvertUtilsBean#register(boolean, boolean, int)}<br>
 * ??,beanUtils,????<br>
 * ?, ,? {@link org.apache.commons.beanutils.Converter},<br>
 *    ??:
 * </p>
 * 
 * <ul>
 * <li>registerPrimitives(throwException);</li>
 * <li>registerStandard(throwException, defaultNull);</li>
 * <li>registerOther(throwException);</li>
 * <li>registerArrays(throwException, defaultArraySize);</li>
 * </ul>
 * 
 *  register,{@link org.apache.commons.beanutils.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);
 * 
 * log.debug(cub.lookup(Long.class));
 * 
 * BeanUtilsBean bub = new BeanUtilsBean(cub, new PropertyUtilsBean());
 * 
 * String name = bub.getProperty(myObject, &quot;name&quot;);
 * log.debug(name);
 * String id = bub.getProperty(myObject, &quot;id&quot;);
 * log.debug(id);
 * 
 * </pre>
 * 
 * </blockquote>
 * 
 * 
 * <h3>{@link PropertyUtils} {@link BeanUtils}:</h3>
 * 
 * <blockquote>
 * <p>
 * {@link PropertyUtils} {@link BeanUtils}????<br>
 * BeanUtils??"Bean"String,<br>
 * PropertyUtils??Object
 * </p>
 * </blockquote>
 * 
 * @author <a href="mailto:venusdrogon@163.com">feilong</a>
 * @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.feilong.commons.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 log. */
    private static final Logger log = 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 {
        //ConvertUtils.register(new DatePatternConverter(DatePattern.commonWithMillisecond), java.util.Date.class);
        //ConvertUtils.register(new DatePatternConverter(DatePattern.commonWithMillisecond), java.sql.Date.class);
        //ConvertUtils.register(new DatePatternConverter(DatePattern.commonWithMillisecond), java.sql.Timestamp.class);
        //ConvertUtils.register(new BigDecimalConverter(null), java.math.BigDecimal.class);

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

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

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

    // [start] cloneBean

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

    // [end]

    // [start] describe BeanMap?

    /**
     * <p>
     * <code>bean</code>???/Map.
     * </p>
     * 
     * ???classObject??classjava.lang.Object.
     * <p>
     * <span style="color:red">:<br>
     * ConvertUtils.register(dateTimeConverter, java.util.Date.class)?</span><br>
     * 
     * , {@link org.apache.commons.beanutils.BeanUtilsBean#getNestedProperty(Object, String)},  ConvertUtilsBean?? <br>
     *  {@link org.apache.commons.beanutils.ConvertUtilsBean#ConvertUtilsBean()}  ?
     * 
     * </p>
     * 
     * @param bean
     *            Bean whose properties are to be extracted
     * 
     * @return Map of property descriptors
     * 
     * @throws BeanUtilException
     *             if IllegalAccessException | InvocationTargetException | NoSuchMethodException
     * @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) throws BeanUtilException {
        try {
            //Return the entire set of properties for which the specified bean provides a read method.
            Map<String, String> propertyMap = BeanUtils.describe(bean);
            return propertyMap;
        } catch (Exception e) {
            log.error(e.getClass().getName(), e);
            throw new BeanUtilException(e);
        }
    }

    // [end]

    // [start] populate properties/map?bean

    /**
     * properties/map?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
     * 
     * @throws BeanUtilException
     *             the bean util exception
     * @see org.apache.commons.beanutils.BeanUtils#populate(Object, Map)
     */
    public static void populate(Object bean, Map<String, ?> properties) throws BeanUtilException {
        try {
            BeanUtils.populate(bean, properties);
        } catch (Exception e) {
            log.error(e.getClass().getName(), e);
            throw new BeanUtilException(e);
        }
    }

    // [end]

    // [start] copyProperties
    /**
     * Properties?, {@link BeanUtils#copyProperties(Object, Object)}<br>
     * ?:?copy???2Bean???ref<br>
     * ?? .
     * 
     * <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 ?? nullPropertyUtils ?? 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
     *            
     * @throws BeanUtilException
     *             the bean util exception
     * @see org.apache.commons.beanutils.BeanUtils#copyProperties(Object, Object)
     * @see org.apache.commons.beanutils.BeanUtils#copyProperty(Object, String, Object)
     */
    public static void copyProperties(Object toObj, Object fromObj) throws BeanUtilException {
        if (null == toObj) {
            throw new IllegalArgumentException("No destination bean/toObj specified");
        }
        if (null == fromObj) {
            throw new IllegalArgumentException("No origin bean/fromObj specified");
        }
        try {
            BeanUtils.copyProperties(toObj, fromObj);
        } catch (Exception e) {
            log.error(e.getClass().getName(), e);
            throw new BeanUtilException(e);
        }
    }

    /**
     * ? {@code fromObj-->toObj}
     * 
     * <pre>
     * java.util.Date  ?copy, ??
     * DateConverter converter = new DateConverter(DatePattern.forToString, Locale.US);
     * ConvertUtils.register(converter, Date.class);
     *   
     * ConvertUtils.register(new DateLocaleConverter(Locale.US, DatePattern.forToString), Date.class); *
     * 
     * BeanUtil.copyProperty(b, a, &quot;date&quot;);
     * </pre>
     * 
     * <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>
     * 
     * @param toObj
     *            
     * @param fromObj
     *            
     * @param filedNames
     *            , can't be null/empty!
     * @throws BeanUtilException
     *             the bean util exception
     * @see #copyProperty(Object, Object, String)
     */
    public static void copyProperties(Object toObj, Object fromObj, String[] filedNames) throws BeanUtilException {
        if (Validator.isNullOrEmpty(filedNames)) {
            throw new NullPointerException("filedNames can't be null/empty!");
        }

        int length = filedNames.length;
        for (int i = 0; i < length; ++i) {
            String filedName = filedNames[i];
            copyProperty(toObj, fromObj, filedName);
        }
    }

    // [end]

    // [start] copyProperty
    /**
     * ? {@code fromObj-->toObj}
     * 
     * <pre>
     * java.util.Date  ?copy, ??
     * DateConverter converter = new DateConverter(DatePattern.forToString, Locale.US);
     * ConvertUtils.register(converter, Date.class);
     *   
     * ConvertUtils.register(new DateLocaleConverter(Locale.US, DatePattern.forToString), Date.class); *
     * 
     * BeanUtil.copyProperty(b, a, &quot;date&quot;);
     * </pre>
     * 
     * <pre>
     * pojo:enterpriseSalesenterpriseSales_form ?&quot;enterpriseName&quot;
     * 
     * enterpriseSales.setEnterpriseName(enterpriseSales_form.getEnterpriseName());
     * 
     * ,?
     * BeanUtil.copyProperty(enterpriseSales,enterpriseSales_form,&quot;enterpriseName&quot;);
     * </pre>
     * 
     * @param toObj
     *            
     * @param fromObj
     *            
     * @param filedName
     *            ??
     * @throws BeanUtilException
     *             the bean util exception
     * @see #getProperty(Object, String)
     * @see #copyProperty(Object, String, Object)
     */
    public static void copyProperty(Object toObj, Object fromObj, String filedName) throws BeanUtilException {
        Object value = getProperty(fromObj, filedName);
        copyProperty(toObj, filedName, value);
    }

    /**
     * bean???namevalue<br>
     * 
     * <pre>
     * java.util.Date  ?copy, ??
     * DateConverter converter = new DateConverter(DatePattern.forToString, Locale.US);
     * ConvertUtils.register(converter, Date.class);
     * BeanUtil.copyProperty(b, a, &quot;date&quot;);
     * </pre>
     * 
     * <pre>
     * : BeanUtils.copyProperty(a, &quot;sample.display&quot;, &quot;second one&quot;);
     * 
     * setProperty
     * 
     * ?bean?,copyProperty()?;
     * setProperty()BeanUtils.populate()(??),?populate(),?override setProperty().
     * ,?,setProperty()???.
     * 
     * </pre>
     * 
     * @param bean
     *            bean
     * @param propertyName
     *            ?Property name (can be nested/indexed/mapped/combo)
     * @param value
     *            value
     * @throws BeanUtilException
     *             the bean util exception
     * @see org.apache.commons.beanutils.BeanUtils#copyProperty(Object, String, Object)
     */
    public static void copyProperty(Object bean, String propertyName, Object value) throws BeanUtilException {
        try {
            BeanUtils.copyProperty(bean, propertyName, value);
        } catch (Exception e) {
            log.error(e.getClass().getName(), e);
            throw new BeanUtilException(e);
        }
    }

    // [end]

    // [start] setProperty

    /**
     *  {@link BeanUtils#setProperty(Object, String, Object)} ?(<b>?</b>).
     * 
     * <pre>
     * 
     * BeanUtils.setProperty(pt1, &quot;x&quot;, &quot;9&quot;); // 9String
     * PropertyUtils.setProperty(pt1, &quot;x&quot;, 9); // int
     * // BeanUtilsPropertyUtils,?int??
     * </pre>
     * 
     * 
     * <pre>
     * {@code
     * getPropertysetProperty,?2?JavaBean????.
     * Company c = new Company();
     * c.setName("Simple");
     * 
     * Simple?????
     * //Simple
     * log.debug(BeanUtils.getProperty(c, "name"));
     * 
     * Map???key??
     * //Map
     *     log.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);
     * log.debug(BeanUtils.getProperty(c, "telephone (2)"));
     * 
     * Indexed??[]??ArrayList???.
     * //index
     *     log.debug(BeanUtils.getProperty(c, "otherInfo[2]"));
     *     BeanUtils.setProperty(c, "product[1]", "NOTES SERVER");
     *     log.debug(BeanUtils.getProperty(c, "product[1]"));
     * 
     * 3????
     * //nest
     *     log.debug(BeanUtils.getProperty(c, "employee[1].name"));
     * 
     * }
     * </pre>
     * 
     * @param bean
     *            Bean on which setting is to be performed
     * @param name
     *            Property name (can be nested/indexed/mapped/combo)
     * @param value
     *            Value to be set
     * @throws BeanUtilException
     *             if IllegalAccessException | InvocationTargetException
     * @see org.apache.commons.beanutils.BeanUtils#setProperty(Object, String, Object)
     * @see org.apache.commons.beanutils.PropertyUtils#setProperty(Object, String, Object)
     * @see com.feilong.commons.core.bean.PropertyUtil#setProperty(Object, String, Object)
     */
    public static void setProperty(Object bean, String name, Object value) throws BeanUtilException {
        try {
            // BeanUtils??
            // ???(?)
            BeanUtils.setProperty(bean, name, value);
        } catch (Exception e) {
            log.error(e.getClass().getName(), e);
            throw new BeanUtilException(e);
        }
    }

    // [end]

    // [start] getProperty

    /**
     *  {@link BeanUtils#getProperty(Object, String)} ?.
     * 
     * <pre>
     * {@code
     * getPropertysetProperty,?2?JavaBean????.
     * Company c = new Company();
     * c.setName("Simple");
     * 
     * Simple?????
     * //Simple
     * log.debug(BeanUtils.getProperty(c, "name"));
     * 
     * Map???key??
     * //Map
     *     log.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);
     * log.debug(BeanUtils.getProperty(c, "telephone (2)"));
     * 
     * Indexed??[]??ArrayList???.
     * //index
     *     log.debug(BeanUtils.getProperty(c, "otherInfo[2]"));
     *     BeanUtils.setProperty(c, "product[1]", "NOTES SERVER");
     *     log.debug(BeanUtils.getProperty(c, "product[1]"));
     * 
     * 3????
     * //nest
     *     log.debug(BeanUtils.getProperty(c, "employee[1].name"));
     * 
     * }
     * </pre>
     * 
     * <h3>{@link BeanUtils#getProperty(Object, String)}&{@link PropertyUtils#getProperty(Object, String)}</h3>
     * 
     * <blockquote>
     * <p>
     * {@link BeanUtils#getProperty(Object, String)} ?String,<br>
     * {@link PropertyUtils#getProperty(Object, String)} Object,???
     * </p>
     * </blockquote>
     * 
     * @param bean
     *            bean
     * @param name
     *            ??
     * @return BeanUtils?
     * @throws BeanUtilException
     *             if IllegalAccessException | InvocationTargetException | NoSuchMethodException
     * @see org.apache.commons.beanutils.BeanUtils#getProperty(Object, String)
     * @see org.apache.commons.beanutils.PropertyUtils#getProperty(Object, String)
     * @see com.feilong.commons.core.bean.PropertyUtil#getProperty(Object, String)
     */
    public static String getProperty(Object bean, String name) throws BeanUtilException {
        // Return the value of the specified property of the specified bean,
        // no matter which property reference format is used, as a String.
        try {
            String propertyValue = BeanUtils.getProperty(bean, name);
            return propertyValue;
        } catch (Exception e) {
            log.error(e.getClass().getName(), e);
            throw new BeanUtilException(e);
        }
    }
    // [end]
}