Java tutorial
/* * 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.discovery.darchrow.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.discovery.darchrow.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("My Name"); * * 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()); * * String name = bub.getProperty(myObject, "name"); * LOGGER.debug(name); * String id = bub.getProperty(myObject, "id"); * LOGGER.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 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.baozun.nebulaplus.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 { //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) * @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) { 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) { LOGGER.error(e.getClass().getName(), e); throw new BeanUtilException(e); } } // [end] // [start] describe BeanMap? /** * <code>bean</code>???/Map. * * <p> * ???classObject??classjava.lang.Object. * </p> * <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 * @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. Map<String, String> propertyMap = BeanUtils.describe(bean); return propertyMap; } catch (Exception e) { LOGGER.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 * @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] // [start] copyProperties /** * Properties?, {@link BeanUtils#copyProperties(Object, Object)}. * * <p> * ?:?copy???2Bean???ref<br> * ?? . * </p> * * <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 * * @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) { if (null == toObj) { throw new NullPointerException("No destination bean/toObj specified"); } if (null == fromObj) { throw new NullPointerException("No origin bean/fromObj specified"); } try { BeanUtils.copyProperties(toObj, fromObj); } catch (Exception e) { LOGGER.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, "date"); * </pre> * * <pre> * pojo:enterpriseSalesenterpriseSales_form ?"enterpriseName","linkMan","phone" * * enterpriseSales.setEnterpriseName(enterpriseSales_form.getEnterpriseName()); * enterpriseSales.setLinkMan(enterpriseSales_form.getLinkMan()); * enterpriseSales.setPhone(enterpriseSales_form.getPhone()); * ,? * BeanUtil.copyProperties(enterpriseSales,enterpriseSales_form,new * String[]{"enterpriseName","linkMan","phone"}); * </pre> * * @param toObj * * @param fromObj * * @param includePropertyNames * ?, can't be null/empty! * @see #copyProperty(Object, Object, String) * @see com.baozun.nebulaplus.bean.BeanUtil#copyProperty(Object, Object, String) */ public static void copyProperties(Object toObj, Object fromObj, String... includePropertyNames) { if (Validator.isNullOrEmpty(includePropertyNames)) { throw new NullPointerException("includePropertyNames can't be null/empty!"); } int length = includePropertyNames.length; for (int i = 0; i < length; ++i) { String filedName = includePropertyNames[i]; copyProperty(toObj, fromObj, filedName); } } //TODO add excludePropertyNames support // [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, "date"); * </pre> * * <pre> * pojo:enterpriseSalesenterpriseSales_form ?"enterpriseName" * * enterpriseSales.setEnterpriseName(enterpriseSales_form.getEnterpriseName()); * * ,? * BeanUtil.copyProperty(enterpriseSales,enterpriseSales_form,"enterpriseName"); * </pre> * * @param toObj * * @param fromObj * * @param filedName * ?? * @see #getProperty(Object, String) * @see #copyProperty(Object, String, Object) */ public static void copyProperty(Object toObj, Object fromObj, String filedName) { Object value = getProperty(fromObj, filedName); copyProperty(toObj, filedName, value); } /** * bean???namevalue. * * <pre> * java.util.Date ?copy, ?? * DateConverter converter = new DateConverter(DatePattern.forToString, Locale.US); * ConvertUtils.register(converter, Date.class); * BeanUtil.copyProperty(b, a, "date"); * </pre> * * <pre> * : BeanUtils.copyProperty(a, "sample.display", "second one"); * * 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 * @see org.apache.commons.beanutils.BeanUtils#copyProperty(Object, String, Object) */ public static void copyProperty(Object bean, String propertyName, Object value) { try { BeanUtils.copyProperty(bean, propertyName, value); } catch (Exception e) { LOGGER.error(e.getClass().getName(), e); throw new BeanUtilException(e); } } // [end] // [start] setProperty /** * {@link BeanUtils#setProperty(Object, String, Object)} ?(<b>?</b>). * * <pre> * * BeanUtils.setProperty(pt1, "x", "9"); // 9String * PropertyUtils.setProperty(pt1, "x", 9); // int * // BeanUtilsPropertyUtils,?int?? * </pre> * * * <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> * * @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 * @see org.apache.commons.beanutils.BeanUtils#setProperty(Object, String, Object) * @see org.apache.commons.beanutils.PropertyUtils#setProperty(Object, String, Object) * @see com.baozun.nebulaplus.bean.PropertyUtil#setProperty(Object, String, Object) */ public static void setProperty(Object bean, String name, Object value) { try { // BeanUtils?? // ???(?) BeanUtils.setProperty(bean, name, value); } catch (Exception e) { LOGGER.error(e.getClass().getName(), e); throw new BeanUtilException(e); } } // [end] // [start] getProperty /** * {@link BeanUtils#getProperty(Object, String)} ?. * * <h3>{@link BeanUtils#getProperty(Object, String) BeanUtils.getProperty}&{@link PropertyUtils#getProperty(Object, String) * PropertyUtils.getProperty}:</h3> * * <blockquote> * <p> * {@link BeanUtils#getProperty(Object, String)} ?String,<br> * {@link PropertyUtils#getProperty(Object, String)} Object,??? * </p> * </blockquote> * * <h3>:</h3> * * <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> * * @param bean * bean * @param name * ?? * @return BeanUtils? * @see org.apache.commons.beanutils.BeanUtils#getProperty(Object, String) * @see org.apache.commons.beanutils.PropertyUtils#getProperty(Object, String) * @see com.baozun.nebulaplus.bean.PropertyUtil#getProperty(Object, String) */ public static String getProperty(Object bean, String name) { // 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) { LOGGER.error(e.getClass().getName(), e); throw new BeanUtilException(e); } } // [end] }