get Array from Object - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

get Array from Object

Demo Code

// This program is free software: you can redistribute it and/or modify
//package com.java2s;
import java.lang.reflect.Array;

public class Main {
    public static void main(String[] argv) {
        Object val = "java2s.com";
        System.out.println(java.util.Arrays.toString(getArray(val)));
    }//from w  w w .j ava 2  s .c om

    public static final Class<?>[] ARRAY_PRIMITIVE_TYPES = { int[].class,
            float[].class, double[].class, boolean[].class, byte[].class,
            short[].class, long[].class, char[].class };

    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[i] = Array.get(val, i);
                }
                break;
            }
        }
        if (outputArray == null) // not primitive type array
            outputArray = (Object[]) val;
        return outputArray;
    }
}

Related Tutorials