集册 Java实例教程 通过展开相应类型返回基元数组。

通过展开相应类型返回基元数组。

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

471
通过展开相应类型返回基元数组。
//来自 时代Java公众号


//package com.nowjava;

import java.lang.reflect.Array;


public class Main {

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

        Object[] sourceArray = new String[] { "1", "abc", "level", null,

                "nowjava.com", "asdf 123" };

        System.out.println(convertToPrimitiveArray(sourceArray));

    }


    /**

     * Returns a primitive array by unwrapping the corresponding types. If the 

     * specified array is not an array of primitive wrapper types (e.g. <code>Integer[]</code>), 

     * an <code>IllegalArgumentException</code> will be thrown.

     * If an array element is <code>null</code>, an <code>IllegalArgumentException</code> 

     * will be thrown.

     * @param sourceArray the array

     * @return the corresponding primitive array

     * @throws IllegalArgumentException if the specified array

     *         is not an array of primitive wrapper types or if an

     *         array element is <code>null</code>

     */

    public static Object convertToPrimitiveArray(Object[] sourceArray) {

        Class componentType = sourceArray.getClass().getComponentType();
        /** from 
        时 代      J a v a   公   众 号 - nowjava.com**/

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

            componentType = Boolean.TYPE;

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

            componentType = Byte.TYPE;

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

            componentType = Character.TYPE;

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

            componentType = Short.TYPE;

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

            componentType = Integer.TYPE;

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

            componentType = Long.TYPE;

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

            componentType = Float.TYPE;

        } else if (componentType.equals(Double.class)) {

            componentType = Double.TYPE;

        } else {

            throw new 
展开阅读全文