集册 Java实例教程 通过包装基元类型返回对象数组。

通过包装基元类型返回对象数组。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

476
通过包装基元类型返回对象数组。
/**from nowjava.com**/


//package com.nowjava;

import java.lang.reflect.Array;


public class Main {

    public static void main(String[] argv) throws Exception {

        Object sourceArray = "nowjava.com";

        System.out.println(java.util.Arrays

                .toString(convertToObjectArray(sourceArray)));

    }


    /**

     * Returns an object array by wrapping primitive types. If the 

     * specified array is of primitive component type, an <code>Object[]</code>

     * with the corresponding wrapper component type is returned.

     * If the specified array is already an object array, the instance is

     * returned unchanged.

     * @param sourceArray the array

     * @return the corresponding object array

     * @throws IllegalArgumentException if the specified object

     *         is not an array (either of reference or primitive

     *         component type)

     */

    public static Object[] convertToObjectArray(Object sourceArray) {

        if (!sourceArray.getClass().isArray()) {

            throw new IllegalArgumentException(

                    "sourceArray must be an array");

        }

        Class componentType = sourceArray.getClass().getComponentType();

        if (!componentType.isPrimitive()) {

            return (Object[]) sourceArray;

        }
        /* from 
        时代Java - nowjava.com*/

        if (componentType.equals(Boolean.TYPE)) {

            componentType = Boolean.class;

        } else if (componentType.equals(Byte.TYPE)) {

            componentType = Byte.class;

        } else if (componentType.equals(Character.TYPE)) {

            componentType = Character.class;

        } else if (componentType.equals(Short.TYPE)) {

            componentType = Short.class;

        } else if (componentType.equals(Integer.TYPE)) {

            componentType = Integer.class;

        } else if (componentType.equals(Long.TYPE)) {

            componentType = Long.class;

        } else if (componentType.equals(Float.TYPE)) {

            componentType = Float.class;

        } else 
展开阅读全文