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.sunchenbin.store.feilong.core.bean; import java.lang.reflect.Array; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.ConvertUtilsBean; import org.apache.commons.beanutils.Converter; import org.apache.commons.beanutils.converters.AbstractConverter; import org.apache.commons.beanutils.converters.BigDecimalConverter; import org.apache.commons.beanutils.converters.BooleanConverter; import org.apache.commons.beanutils.converters.IntegerConverter; import org.apache.commons.beanutils.converters.LongConverter; import org.apache.commons.beanutils.converters.NumberConverter; import org.apache.commons.collections4.EnumerationUtils; import org.apache.commons.collections4.IteratorUtils; import org.apache.commons.collections4.iterators.EnumerationIterator; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import com.sunchenbin.store.feilong.core.lang.ArrayUtil; import com.sunchenbin.store.feilong.core.lang.StringUtil; import com.sunchenbin.store.feilong.core.util.Validator; /** * ?. * * <h3>?:</h3> * * <blockquote> * <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> * </blockquote> * * <h3>{@link ConvertUtils} :</h3> * * <blockquote> * <table border="1" cellspacing="0" cellpadding="4"> * <tr style="background-color:#ccccff"> * <th align="left"></th> * <th align="left"></th> * </tr> * <tr valign="top"> * <td>{@link ConvertUtils#convert(Object)}</td> * <td>value?string.<br> * valuearray, ?string. <code>java.lang.String</code> {@link Converter},? Object->String conversions ( * ? toString()) <br> * see {@link ConvertUtilsBean#convert(Object)}</td> * </tr> * <tr valign="top" style="background-color:#eeeeff"> * <td>{@link ConvertUtils#convert(String, Class)}</td> * <td>String value? Class (?),?string. <br> * see {@link ConvertUtilsBean#convert(String, Class)}</td> * </tr> * <tr valign="top"> * <td>{@link ConvertUtils#convert(String[], Class)}</td> * <td>?class. <br> * Class, . ?. <br> * see {@link ConvertUtilsBean#convert(String[], Class)} <br> * see {@link #convert(String[], Class)}</td> * </tr> * <tr valign="top" style="background-color:#eeeeff"> * <td>{@link ConvertUtils#convert(Object, Class)}</td> * <td>value?Class,Class?, value.<br> * see {@link ConvertUtilsBean#convert(Object, Class)}<br> * see {@link #convert(Object, Class)}</td> * </tr> * </table> * </blockquote> * * <p> * standard {@link Converter} instances are provided for all of the following destination Classes: * </p> * * <blockquote> * <table border="1" cellspacing="0" cellpadding="4"> * <tr style="background-color:#ccccff"> * <th align="left"></th> * <th align="left"></th> * </tr> * <tr valign="top"> * <td>java.lang.BigDecimal</td> * <td><span style="color:red">no default value</span></td> * </tr> * <tr valign="top" style="background-color:#eeeeff"> * <td>java.lang.BigInteger</td> * <td><span style="color:red">no default value</span></td> * </tr> * <tr valign="top"> * <td>boolean and java.lang.Boolean</td> * <td>default to false</td> * </tr> * <tr valign="top" style="background-color:#eeeeff"> * <td>byte and java.lang.Byte</td> * <td>default to zero</td> * </tr> * <tr valign="top"> * <td>char and java.lang.Character</td> * <td>default to a space</td> * </tr> * <tr valign="top" style="background-color:#eeeeff"> * <td>java.lang.Class</td> * <td><span style="color:red">no default value</span></td> * </tr> * <tr valign="top"> * <td>double and java.lang.Double</td> * <td>default to zero</td> * </tr> * <tr valign="top" style="background-color:#eeeeff"> * <td>float and java.lang.Float</td> * <td>default to zero</td> * </tr> * <tr valign="top"> * <td>int and java.lang.Integer</td> * <td>default to zero</td> * </tr> * <tr valign="top" style="background-color:#eeeeff"> * <td>long and java.lang.Long</td> * <td>default to zero</td> * </tr> * <tr valign="top"> * <td>short and java.lang.Short</td> * <td>default to zero</td> * </tr> * <tr valign="top" style="background-color:#eeeeff"> * <td>java.lang.String</td> * <td>default to null</td> * </tr> * <tr valign="top"> * <td>java.io.File</td> * <td><span style="color:red">no default value</span></td> * </tr> * <tr valign="top" style="background-color:#eeeeff"> * <td>java.net.URL</td> * <td><span style="color:red">no default value</span></td> * </tr> * <tr valign="top"> * <td>java.sql.Date</td> * <td><span style="color:red">no default value</span></td> * </tr> * <tr valign="top" style="background-color:#eeeeff"> * <td>java.sql.Time</td> * <td><span style="color:red">no default value</span></td> * </tr> * <tr valign="top"> * <td>java.sql.Timestamp</td> * <td><span style="color:red">no default value</span></td> * </tr> * </table> * </blockquote> * * @author feilong * @version 1.3.0 2015724 ?7:43:33 * @see org.apache.commons.beanutils.ConvertUtils * @see org.apache.commons.beanutils.converters.AbstractConverter#handleMissing(Class) * @see org.apache.commons.beanutils.locale.LocaleConvertUtils * @since 1.3.0 */ public final class ConvertUtil { /** Don't let anyone instantiate this class. */ private ConvertUtil() { //AssertionError?. ?????. ???. //see Effective Java 2nd throw new AssertionError("No " + getClass().getName() + " instances for you!"); } /** * object ??boolean. * * <h3>:</h3> * * <blockquote> * * <ul> * <li>if "true", "yes", "y", "on", "1", will return true</li> * <li>if "false", "no", "n", "off", "0", will return false</li> * <li>else will throw conversionException, but in * {@link org.apache.commons.beanutils.converters.AbstractConverter#handleError(Class, Object, Throwable) handleError(Class, Object, * Throwable)} method will return default value, {@link BooleanConverter} defaultValue pls see * {@link org.apache.commons.beanutils.ConvertUtilsBean#registerStandard(boolean, boolean) registerStandard(boolean, boolean)}</li> * </ul> * * <p> * you also can call {@link org.apache.commons.beanutils.converters.BooleanConverter#BooleanConverter(String[], String[], Object) * BooleanConverter(String[], String[], Object)} set trueStrings and falseStrings * </p> * </blockquote> * * <h3> {@link Boolean#parseBoolean(String)}:</h3> * * <blockquote> * <p> * {@link Boolean#parseBoolean(String)}, <code>(String != null) && String.equalsIgnoreCase("true")</code> true * </p> * </blockquote> * * @param toBeConvertedValue * object * @return boolean * @see #convert(Object, Class) * @see org.apache.commons.beanutils.converters.BooleanConverter * @see java.lang.Boolean#parseBoolean(String) */ public static Boolean toBoolean(Object toBeConvertedValue) { return convert(toBeConvertedValue, Boolean.class); } /** * object?integer. * * <p> * converted is missing or an error occurs converting the value,<span style="color:red">return null</span> * </p> * * @param toBeConvertedValue * * @return the integer * @see org.apache.commons.beanutils.converters.IntegerConverter */ public static Integer toInteger(Object toBeConvertedValue) { IntegerConverter integerConverter = new IntegerConverter(null); return integerConverter.convert(Integer.class, toBeConvertedValue); } /** * object?? {@link java.math.BigDecimal}. * * <p> * converted is missing or an error occurs converting the value,<span style="color:red">return null</span> * </p> * * <h3>{@link java.lang.Double} ? {@link java.math.BigDecimal}?:</h3> * * <blockquote> * * <p> * <span style="color:red">?? {@link BigDecimal#valueOf(double)}</span>,? {@code new BigDecimal(double)},?? JDK API<br> * </p> * * <ul> * <li>{@code new BigDecimal(0.1) ====> 0.1000000000000000055511151231257827021181583404541015625}</li> * <li>{@code BigDecimal.valueOf(0.1) ====> 0.1}</li> * </ul> * * {@link NumberConverter#toNumber(Class, Class, Number) * NumberConverter#toNumber(Class, Class, Number)},? {@link java.lang.Double} ? {@link java.math.BigDecimal} </blockquote> * * @param toBeConvertedValue * * @return BigDecimal * @see #convert(Object, Class) * @see org.apache.commons.beanutils.converters.NumberConverter#toNumber(Class, Class, Number) * @see org.apache.commons.beanutils.converters.BigDecimalConverter */ public static BigDecimal toBigDecimal(Object toBeConvertedValue) { BigDecimalConverter bigDecimalConverter = new BigDecimalConverter(null); return bigDecimalConverter.convert(BigDecimal.class, toBeConvertedValue); } //************************************************************************************************* /** * ??. * * <h3> Array ? String</h3> * * <blockquote> * * <p> * ?? {@link org.apache.commons.beanutils.converters.ArrayConverter#convertToString(Object) ArrayConverter#convertToString(Object)} <br> * * ?, ? object , {@link java.lang.reflect.Array#get(Object, int) Array#get(Object, int)} ??,<br> * ??, object?? {@link org.apache.commons.beanutils.converters.ArrayConverter#convertToCollection(Class, Object) * ArrayConverter#convertToCollection(Class, Object)} ?? {@link java.util.Collection#iterator()} * </p> * * <p> * object?? {@link org.apache.commons.beanutils.converters.ArrayConverter#convertToCollection(Class, Object) * ArrayConverter#convertToCollection(Class, Object)},: * </p> * </blockquote> * * <ul> * <li>The string is expected to be a comma-separated list of values.</li> * <li>?'{' and '}'.</li> * <li>??.</li> * <li>Elements in the list may be delimited by single or double quotes. Within a quoted elements, the normal Java escape sequences are * valid.</li> * </ul> * * <p> * : * </p> * * <blockquote> * <table border="1" cellspacing="0" cellpadding="4"> * <tr style="background-color:#ccccff"> * <th align="left"></th> * <th align="left"></th> * </tr> * <tr valign="top"> * <td>int defaultSize</td> * <td>? or if less than zero indicates that a <code>null</code> default value should be used.</td> * </tr> * <tr valign="top" style="background-color:#eeeeff"> * <td>char delimiter = ','</td> * <td>,?string</td> * </tr> * <tr valign="top"> * <td>char[] allowedChars = new char[] {'.', '-'}</td> * <td>{@link java.io.StreamTokenizer}</td> * </tr> * <tr valign="top" style="background-color:#eeeeff"> * <td>boolean onlyFirstToString = true;</td> * <td>?</td> * </tr> * </table> * </blockquote> * * @param toBeConvertedValue * ? * @return the string * @see org.apache.commons.beanutils.converters.ArrayConverter#convertToString(Object) * @see org.apache.commons.beanutils.ConvertUtils#convert(Object) * @see org.apache.commons.beanutils.ConvertUtilsBean#convert(Object) * @see org.apache.commons.beanutils.converters.StringConverter * * @see java.util.Arrays#toString(Object[]) */ public static String toString(Object toBeConvertedValue) { return convert(toBeConvertedValue, String.class); } /** * ? <code>collection</code>??. * * <h3>:</h3> * * <blockquote> * * <pre> * List<String> list = new ArrayList<String>(); * list.add("feilong"); * list.add(""); * list.add("xinge"); * * ToStringConfig toStringConfig = new ToStringConfig(","); * toStringConfig.setIsJoinNullOrEmpty(false); * * assertEquals("feilong,xinge", ConvertUtil.toString(toStringConfig, list)); * </pre> * * </blockquote> * * @param toStringConfig * * @param collection * ?, ?,collection * @return collection isNullOrEmpty,null<br> * toStringConfig null, {@link ToStringConfig#DEFAULT_CONNECTOR} <br> * ?null,,toStringConfig.getConnector() * @see #toString(ToStringConfig, Object...) * @since 1.4.0 */ public static String toString(ToStringConfig toStringConfig, final Collection<?> collection) { if (Validator.isNullOrEmpty(collection)) { return StringUtils.EMPTY; } Object[] array = collection.toArray(); return toString(toStringConfig, array); } /** * {@link ToStringConfig} ? . * * <p style="color:green"> * ??, Integer [] arrays ? int []arrays * </p> * * <code> * <pre> * Example 1: * ArrayUtil.toString(new ToStringConfig(),"a","b") return "a,b" * * Example 2: * ToStringConfig toStringConfig=new ToStringConfig(","); * toStringConfig.setIsJoinNullOrEmpty(false); * ArrayUtil.toString(new ToStringConfig(),"a","b",null) return "a,b" * * Example 3: * int[] ints = { 2, 1 }; * ArrayUtil.toString(new ToStringConfig(),ints) return "2,1" * </pre> * </code> * * @param toStringConfig * the join string entity * @param arrays * <span style="color:red">??, Integer []arrays ? int []arrays</span> * @return <ul> * <li> arrays null Empty ,null</li> * <li>?, {@link ToStringConfig#getConnector()}</li> * </ul> * @see org.apache.commons.lang3.builder.ToStringStyle * @since 1.4.0 */ public static String toString(ToStringConfig toStringConfig, Object... arrays) { if (Validator.isNullOrEmpty(arrays)) { return StringUtils.EMPTY; } //************************************************************************ Object[] operateArray = toObjects(arrays); ToStringConfig useToStringConfig = null == toStringConfig ? new ToStringConfig() : toStringConfig; String connector = useToStringConfig.getConnector(); //************************************************************************ StringBuilder sb = new StringBuilder(); for (Object obj : operateArray) { //nullempty,??,, if (Validator.isNullOrEmpty(obj) && !useToStringConfig.getIsJoinNullOrEmpty()) { continue; } //value?,?: valuenull,StringBuilder "null" ,? java.lang.AbstractStringBuilder#append(String) sb.append(null == obj ? StringUtils.EMPTY : "" + obj); //see StringUtils.defaultString(t) if (null != connector) {//???? ?Validator.isNullOrEmpty? sb.append(connector);// connector, ???,?? } } return StringUtil.substringWithoutLast(sb, connector); } //********************************************************************************************** /** * ??. * * @param <T> * the generic type * @param collection * ? * @return Enumeration * @see Collections#enumeration(Collection) * @since 1.4.0 */ public static <T> Enumeration<T> toEnumeration(final Collection<T> collection) { return Collections.enumeration(collection); } /** * ??. * * @param <T> * the generic type * @param enumeration * the enumeration * @return if Validator.isNullOrEmpty(enumeration), return {@link Collections#emptyList()},emptyList???<br> * else return {@link Collections#list(Enumeration)} * @see Collections#emptyList() * @see Collections#EMPTY_LIST * @see Collections#list(Enumeration) * @see EnumerationUtils#toList(Enumeration) * @since 1.0.7 */ public static <T> List<T> toList(final Enumeration<T> enumeration) { if (Validator.isNullOrEmpty(enumeration)) { return Collections.emptyList(); } return Collections.list(enumeration); } /** * ? ({@link java.util.ArrayList ArrayList}),list?add?. * <p> * ? :{@link java.util.Arrays#asList(Object...) Arrays#asList(Object...)}list, {@link java.util.Collection#add(Object) * Collection#add(Object)}<br> * , {@link ArrayList#ArrayList(java.util.Collection)} ??? * </p> * * @param <T> * the generic type * @param arrays * T * @return ? List(ArrayList)<br> * if Validator.isNullOrEmpty(arrays), return null,else return {@code new ArrayList<T>(Arrays.asList(arrays));} * @see java.util.Arrays#asList(Object...) */ public static <T> List<T> toList(T[] arrays) { if (Validator.isNullOrEmpty(arrays)) { return Collections.emptyList(); } // Arrays.asList(arrays) ArraysArrayList,AbstractListadd, strList.add("c");! return new ArrayList<T>(Arrays.asList(arrays)); } /** * ??. * * @param <T> * the generic type * @param collection * collection * @param arrayComponentType * Class * @return ,if null == collection or arrayClass == null,return NullPointerException * @see java.lang.reflect.Array#newInstance(Class, int) * @see java.lang.reflect.Array#newInstance(Class, int...) * @see java.util.Collection#toArray() * @see java.util.Collection#toArray(Object[]) * @see java.util.List#toArray() * @see java.util.List#toArray(Object[]) * @see java.util.Vector#toArray() * @see java.util.Vector#toArray(Object[]) * @see java.util.LinkedList#toArray() * @see java.util.LinkedList#toArray(Object[]) * @see java.util.ArrayList#toArray() * @see java.util.ArrayList#toArray(Object[]) * @see org.apache.commons.collections4.IteratorUtils#toArray(Iterator,Class) * @since 1.2.2 */ public static <T> T[] toArray(Collection<T> collection, Class<T> arrayComponentType) { if (null == collection) { throw new NullPointerException("collection must not be null"); } if (arrayComponentType == null) { throw new NullPointerException("Array ComponentType must not be null"); } // alength0,???API??size,?. // ?alengthCollectionsize????API?. @SuppressWarnings("unchecked") T[] array = (T[]) Array.newInstance(arrayComponentType, collection.size()); //?,toArray(new Object[0]) toArray() ?. return collection.toArray(array); } /** * ?. * * <p> * <code>arrays</code>,?. * </p> * * @param <T> * the generic type * @param arrays * the arrays * @return the object[] * @since 1.4.0 */ private static <T> Object[] toObjects(T... arrays) { if (Validator.isNullOrEmpty(arrays)) { return ArrayUtils.EMPTY_STRING_ARRAY; } if (arrays.length > 1) { return arrays; } Object o = arrays[0]; if (isPrimitiveArray(o)) { return primitiveArrayToObjectArray(o); } return arrays; } /** * ? Primitive. * * @param o * the o * @return true, if checks if is primitive array * * @since 1.4.0 */ private static boolean isPrimitiveArray(Object o) { // Allocate a new Array Class<? extends Object> klass = o.getClass(); if (!klass.isArray()) { return false; } Class<?> componentType = klass.getComponentType(); // return componentType.isPrimitive(); } /** * To objects. * * @param primitiveArray * the o * @return the object[] * @since 1.4.0 */ private static Object[] primitiveArrayToObjectArray(Object primitiveArray) { int length = ArrayUtils.getLength(primitiveArray); Object[] returnStringArray = new Object[length]; for (int i = 0; i < length; ++i) { Object element = ArrayUtil.getElement(primitiveArray, i); returnStringArray[i] = element; } return returnStringArray; } /** * ?long. * * <p> * converted is missing or an error occurs converting the value,<span style="color:red">return null</span> * </p> * * @param toBeConvertedValue * ?. * @return the long * @see #convert(Object, Class) * @see org.apache.commons.beanutils.converters.LongConverter */ public static Long toLong(Object toBeConvertedValue) { LongConverter longConverter = new LongConverter(null); return longConverter.convert(Long.class, toBeConvertedValue); } /** * ??Integer . * * @param toBeConvertedValue * the to be converted value * @return the integer[] * @see #convert(Object, Class) * @see org.apache.commons.beanutils.converters.ArrayConverter */ public static Integer[] toIntegers(Object toBeConvertedValue) { return convert(toBeConvertedValue, Integer[].class); } /** * To long array. * * @param toBeConvertedValue * the to be converted value * @return the long[] * @see org.apache.commons.beanutils.ConvertUtils#convert(Object, Class) * @see org.apache.commons.beanutils.converters.ArrayConverter * @see #convert(Object, Class) */ public static Long[] toLongs(Object toBeConvertedValue) { return convert(toBeConvertedValue, Long[].class); } /** * ?string. * * <p> * Parse an incoming String of the form similar to an array initializer in the Java language into a <code>List</code> individual Strings * for each element, according to the following rules. * </p> * <ul> * <li>The string is expected to be a comma-separated list of values.</li> * <li>The string may optionally have matching '{' and '}' delimiters around the list.</li> * <li>Whitespace before and after each element is stripped.</li> * <li>Elements in the list may be delimited by single or double quotes. Within a quoted elements, the normal Java escape sequences are * valid.</li> * </ul> * * @param toBeConvertedValue * the to be converted value * @return the string[] * @see org.apache.commons.beanutils.converters.AbstractArrayConverter#parseElements(String) * @see #convert(Object, Class) * @since 1.4.0 */ public static String[] toStrings(Object toBeConvertedValue) { return convert(toBeConvertedValue, String[].class); } /** * ??Iterator. * * <h3>?:</h3> * * <blockquote> * <ul> * <li>?,{@link ConvertUtil#toStrings(Object)} ?</li> * <li></li> * <li>{@link java.util.Map}, {@link java.util.Map#values()} ?{@link java.util.Iterator}</li> * <li>{@link java.util.Collection}</li> * <li>{@link java.util.Iterator}</li> * <li>{@link java.util.Enumeration}</li> * <li>{@link java.util.Dictionary}</li> * <li>{@link org.w3c.dom.Node}</li> * <li>{@link org.w3c.dom.NodeList}</li> * </ul> * </blockquote> * * @param <T> * the generic type * @param object * <ul> * <li>?,{@link ConvertUtil#toStrings(Object)} ?</li> * <li></li> * <li>{@link java.util.Map}, {@link java.util.Map#values()} ?{@link java.util.Iterator}</li> * <li>{@link java.util.Collection}</li> * <li>{@link java.util.Iterator}</li> * <li>{@link java.util.Enumeration}</li> * <li>{@link java.util.Dictionary}</li> * <li>{@link org.w3c.dom.Node}</li> * <li>{@link org.w3c.dom.NodeList}</li> * </ul> * @return <ul> * <li> null == object null,</li> * <li>?? {@link IteratorUtils#getIterator(Object)}</li> * </ul> * @see Collection#iterator() * @see EnumerationIterator#EnumerationIterator(Enumeration) * @see IteratorUtils#getIterator(Object) * @see "org.apache.taglibs.standard.tag.common.core.ForEachSupport#supportedTypeForEachIterator(Object)" * @since Commons Collections4.0 */ @SuppressWarnings("unchecked") public static <T> Iterator<T> toIterator(Object object) { if (null == object) { return null; } // ? if (object instanceof String) { return toIterator(toStrings(object)); } return (Iterator<T>) IteratorUtils.getIterator(object); } /** * value?Class,Class?,value.. * * <h3>?:</h3> * * <blockquote> * * <ul> * <li> value <code>value.getClass().isArray()</code> {@link Collection},<span style="color:red">?</span>? * {@link AbstractConverter#convert(Class, Object)} , {@link AbstractConverter#convertArray(Object)} </li> * </ul> * * </blockquote> * * @param <T> * the generic type * @param value * the value * @param targetType * the target type * @return the t * @see org.apache.commons.beanutils.ConvertUtils#convert(Object, Class) * @see org.apache.commons.beanutils.converters.AbstractConverter#convert(Class, Object) */ @SuppressWarnings("unchecked") public static <T> T convert(Object value, Class<T> targetType) { return (T) org.apache.commons.beanutils.ConvertUtils.convert(value, targetType); } /** * Convert an array of specified values to an array of objects of the specified class (if possible). * * <p> * If the specified Java class is itself an array class, this class will be the type of the returned value.<br> * Otherwise, an array will be constructed whose component type is the specified class. * </p> * * @param <T> * the generic type * @param values * the values * @param targetType * the target type * @return the t[] * @see org.apache.commons.beanutils.ConvertUtils#convert(String[], Class) * @see org.apache.commons.beanutils.ConvertUtilsBean#convert(String[], Class) */ @SuppressWarnings("unchecked") public static <T> T[] convert(String[] values, Class<T> targetType) { return (T[]) org.apache.commons.beanutils.ConvertUtils.convert(values, targetType); } }