集册 Java实例教程 从对象获取数组

从对象获取数组

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

528
从对象获取数组

// This program is free software: you can redistribute it and/or modify

//package com.nowjava;

import java.lang.reflect.Array;
/*来 自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m*/

public class Main {

    public static void main(String[] argv) {

        Object val = "nowjava.com";

        System.out.println(java.util.Arrays.toString(getArray(val)));

    }


    public static final Class<?>[] ARRAY_PRIMITIVE_TYPES = { int[].class,

            float[].class, double[].class, boolean[].class, byte[].class,

            short[].class, long[].class, char[].class };

            /* 
            *来 自
             nowjava.com - 时代Java
            */

    public static Object[] getArray(Object val) {

        Class<?> valKlass = val.getClass();

        Object[] outputArray = null;

        for (Class<?> arrKlass : ARRAY_PRIMITIVE_TYPES) {

            if (valKlass.isAssignableFrom(arrKlass)) {

                int arrlength = Array.getLength(val);

                outputArray = new Object[arrlength];

                for (int i = 0; i < arrlength; ++i) {

                    outputArray
展开阅读全文