com.discovery.darchrow.lang.ObjectUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.discovery.darchrow.lang.ObjectUtil.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.discovery.darchrow.lang;

import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.iterators.EnumerationIterator;

import com.discovery.darchrow.io.SerializableUtil;
import com.discovery.darchrow.util.Validator;

/**
 * object.
 * 
 * @author  2010-4-5 ?11:00:54
 * @since 1.0.0
 */
public final class ObjectUtil {

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

    /**
     * ?.
     * 
     * <p>
     * <span style="color:red">?? {@link java.io.Serializable Serializable} {@link java.io.Externalizable Externalizable} ??
     * {@link java.io.ObjectInputStream ObjectInputStream}/{@link java.io.ObjectOutputStream ObjectOutputStream}??</span>
     * </p>
     *
     * @param serializable
     *            the object
     * @return the int
     * @see ByteArrayOutputStream#size()
     * @see com.baozun.nebulaplus.io.SerializableUtil#size(Serializable)
     * @since 1.0.7
     */
    public static int size(Serializable serializable) {
        return SerializableUtil.size(serializable);
    }

    /**
     * ?
     * <ul>
     * <li>?</li>
     * <li></li>
     * <li>{@link java.util.Map},key ?{@link java.util.Iterator}</li>
     * <li>{@link java.util.Collection}</li>
     * <li>{@link java.util.Iterator}</li>
     * <li>{@link java.util.Enumeration}</li>
     * </ul>
     * ?Iterator.
     *
     * @param <T>
     *            the generic type
     * @param object
     *            <ul>
     *            <li>?</li>
     *            <li></li>
     *            <li>map,key ?Iterator</li>
     *            <li>Collection</li>
     *            <li>Iterator</li>
     *            <li>Enumeration</li>
     *            </ul>
     * @return <ul>
     *         <li> null == object null,</li>
     *         <li>??Iterator</li>
     *         </ul>
     * @see ArrayUtil#toIterator(Object)
     * @see Collection#iterator()
     * @see Iterator
     * @see Map#keySet()
     * @see Set#iterator()
     * @see org.apache.commons.collections.iterators.EnumerationIterator#EnumerationIterator(Enumeration)
     * @since Commons Collections 1.0
     */
    @SuppressWarnings("unchecked")
    public static final <T> Iterator<T> toIterator(Object object) {
        if (null == object) {
            return null;
        }
        // object ?
        // 
        if (object.getClass().isArray()) {
            return ArrayUtil.toIterator(object);
        }
        // Collection
        else if (object instanceof Collection) {
            return ((Collection<T>) object).iterator();
        }
        // Iterator
        else if (object instanceof Iterator) {
            return (Iterator<T>) object;
        }
        // Enumeration
        else if (object instanceof Enumeration) {
            Enumeration<T> enumeration = (Enumeration<T>) object;
            EnumerationIterator enumerationIterator = new EnumerationIterator(enumeration);
            return enumerationIterator;
        }
        // map
        else if (object instanceof Map) {
            Set<T> keySet = ((Map<T, ?>) object).keySet();
            return keySet.iterator();
        }
        // ?
        else if (object instanceof String) {
            String[] strings = object.toString().split(",");
            return ArrayUtil.toIterator(strings);
        } else {
            throw new IllegalArgumentException("param object:[" + object + "] don't support convert to Iterator.");
        }
    }

    //****************************************************************************************
    /**
     * ?? <br>
     * ?,object.equals(object2)?true
     * 
     * @param object
     *            object
     * @param object2
     *            object2
     * @return ?,object.equals(object2)?true
     */
    public static final boolean equalsNotNull(Object object, Object object2) {
        if (Validator.isNotNullOrEmpty(object) && Validator.isNotNullOrEmpty(object2)) {
            return object.equals(object2);
        }
        return false;
    }

    /**
     * ?,?null.
     * 
     * @param object
     *            object
     * @param object2
     *            object2
     * @param nullTypeFlag
     *            null"",false ?
     * @return ?
     * @see java.util.Objects#equals(Object, Object)
     * @see org.apache.commons.lang3.ObjectUtils#equals(Object, Object)
     */
    public static final Boolean equals(Object object, Object object2, boolean nullTypeFlag) {
        //TODO Either override Object.equals(Object), or totally rename the method to prevent any confusion.
        //Methods named "equals" should override Object.equals(Object)
        if (object == object2) {
            return true;
        }
        // object 
        if (null == object) {
            // null""
            if (nullTypeFlag) {
                if ("".equals(trim(object2))) {
                    return true;
                }
            }
        } else {
            // null""
            if ("".equals(trim(object))) {
                if (null == object2) {
                    if (nullTypeFlag) {
                        return true;
                    }
                } else {
                    if ("".equals(trim(object2))) {
                        return true;
                    }
                }
            } else {
                return object.equals(object2);
            }
        }
        return false;
    }

    /**
     * ?,?null.
     * 
     * @param object
     *            object
     * @param object2
     *            object2
     * @return ? null"",false ?
     * @see java.util.Objects#equals(Object, Object)
     * @see org.apache.commons.lang3.ObjectUtils#equals(Object, Object)
     */
    public static final Boolean equals(Object object, Object object2) {
        //TODO Either override Object.equals(Object), or totally rename the method to prevent any confusion.
        //Methods named "equals" should override Object.equals(Object)
        return equals(object, object2, false);
    }

    //****************************************************************************************

    /**
     * ?boolean?.
     * 
     * @param object
     *            
     * @return true
     */
    public static final Boolean isBoolean(Object object) {
        return object instanceof Boolean;
    }

    /**
     * ?Integer.
     * 
     * @param object
     *            
     * @return true
     */
    public static final Boolean isInteger(Object object) {
        return object instanceof Integer;
    }

    /**
     * object ??boolean.
     * 
     * @param object
     *            object
     * @return boolean
     */
    public static final Boolean toBoolean(Object object) {
        if (null == object) {
            throw new IllegalArgumentException("object can't be null/empty!");
        }
        return Boolean.parseBoolean(object.toString());
    }

    /**
     * object?integer.
     *
     * @param value
     *            
     * @return <ul>
     *         <li>valuenull,null</li>
     *         <li>valueInteger,?? (Integer) value</li>
     *         <li>? new Integer(value.toString().trim())</li>
     *         <li>value??integer  IllegalArgumentException</li>
     *         </ul>
     */
    public static final Integer toInteger(Object value) {
        if (Validator.isNullOrEmpty(value)) {
            return null;
        }

        if (value instanceof Integer) {
            return (Integer) value;
        }

        try {
            return new Integer(trim(value));
        } catch (Exception e) {
            throw new IllegalArgumentException("Input param:[\"" + value + "\"], convert to integer exception", e);
        }
    }

    /**
     * object??BigDecimal.
     * 
     * <h3>?: double ? BigDecimal:</h3>
     * 
     * <blockquote>
     * 
     * <pre>
     * <span style="color:red">?? BigDecimal.valueOf</span>?new BigDecimal(double)?? JDK API
     * new BigDecimal(0.1) ====&gt;   0.1000000000000000055511151231257827021181583404541015625
     * BigDecimal.valueOf(0.1) ====&gt;  0.1
     * </pre>
     * 
     * </blockquote>
     * 
     * @param value
     *            
     * @return BigDecimal
     */
    public static final BigDecimal toBigDecimal(Object value) {
        if (Validator.isNullOrEmpty(value)) {
            return null;
        }

        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }

        // double ? BigDecimal?? BigDecimal.valueOf?new BigDecimal(double)?? JDK API
        //new BigDecimal(0.1) ====>   0.1000000000000000055511151231257827021181583404541015625
        //BigDecimal.valueOf(0.1) ====>  0.1

        //?string ?
        return new BigDecimal(trim(value));
    }

    /**
     * ?long.
     * 
     * @param value
     *            ?.
     * @return long ??,??null.
     */
    public static final Long toLong(Object value) {
        if (Validator.isNullOrEmpty(value)) {
            return null;
        }

        if (value instanceof Long) {
            return (Long) value;
        }
        return Long.parseLong(value.toString());
    }

    /**
     * Object to double.
     * 
     * @param value
     *            the value
     * @return the double
     */
    public static final Double toDouble(Object value) {
        if (Validator.isNullOrEmpty(value)) {
            return null;
        }

        if (value instanceof Double) {
            return (Double) value;
        }
        return new Double(value.toString());
    }

    /**
     * object to float.
     * 
     * @param value
     *            the value
     * @return the float
     */
    public static final Float toFloat(Object value) {
        if (Validator.isNullOrEmpty(value)) {
            return null;
        }

        if (value instanceof Float) {
            return (Float) value;
        }
        return new Float(value.toString());
    }

    /**
     * object to short.
     * 
     * @param value
     *            the value
     * @return the short
     */
    public static final Short toShort(Object value) {
        if (Validator.isNullOrEmpty(value)) {
            return null;
        }

        if (value instanceof Short) {
            return (Short) value;
        }
        return new Short(value.toString());
    }

    /**
     * ??.
     * 
     * @param value
     *            ?
     * @return <ul>
     *         <li>{@code (null == value) =====>return null}</li>
     *         <li>{@code (value instanceof String) =====>return (String) value}</li>
     *         <li>{@code return value.toString()}</li>
     *         <li> {@link java.util.Arrays#toString(Object[])}</li>
     *         </ul>
     * @since 1.0
     */
    public static final String toString(Object value) {
        if (null == value) {
            return null;
        }
        if (value instanceof String) {
            return (String) value;
        }
        if (value instanceof Object[]) {
            return Arrays.toString((Object[]) value);
        }

        //***************************************************************
        // primitive ints
        if (value instanceof int[]) {
            return Arrays.toString((int[]) value);
        }

        // primitive long
        if (value instanceof long[]) {
            return Arrays.toString((long[]) value);
        }

        // primitive float
        if (value instanceof float[]) {
            return Arrays.toString((float[]) value);
        }

        // primitive double
        if (value instanceof double[]) {
            return Arrays.toString((double[]) value);
        }

        // primitive char
        if (value instanceof char[]) {
            return Arrays.toString((char[]) value);
        }

        // primitive boolean
        if (value instanceof boolean[]) {
            return Arrays.toString((boolean[]) value);
        }

        // primitive byte
        if (value instanceof byte[]) {
            return Arrays.toString((byte[]) value);
        }

        // primitive short
        if (value instanceof short[]) {
            return Arrays.toString((short[]) value);
        }
        return value.toString();
    }

    /**
     * object to T.
     * 
     * @param <T>
     *            the generic type
     * @param value
     *            the value
     * @param klass
     *            the class1
     * @return if null==value return null,else to class convert<br>
     *         ?class,? (T) value
     */
    @SuppressWarnings("unchecked")
    // XXX
    public static final <T> T toT(Object value, Class<?> klass) {
        if (null == value) {
            return null;
        }
        if (klass == String.class) {
            return (T) toString(value);
        } else if (klass == Boolean.class) {
            return (T) toBoolean(value);
        } else if (klass == Integer.class) {
            return (T) toInteger(value);
        } else if (klass == BigDecimal.class) {
            return (T) toBigDecimal(value);
        } else if (klass == Long.class) {
            return (T) toLong(value);
        } else if (klass == Double.class) {
            return (T) toDouble(value);
        } else if (klass == Float.class) {
            return (T) toFloat(value);
        } else if (klass == Short.class) {
            return (T) toShort(value);
        }
        return (T) value;
    }

    /**
     * .
     * 
     * <pre>
     * trim(null) --------&gt; &quot;&quot;
     * trim(&quot;null&quot;) --------&gt; &quot;null&quot;
     * 
     * </pre>
     * 
     * @param obj
     *            obj
     * @return 
     */
    public static final String trim(Object obj) {
        return obj == null ? "" : obj.toString().trim();
    }
}