Java examples for Collection Framework:Array Element
Returns an object array by wrapping primitive types.
//package com.java2s; import java.lang.reflect.Array; public class Main { public static void main(String[] argv) throws Exception { Object sourceArray = "java2s.com"; System.out.println(java.util.Arrays .toString(convertToObjectArray(sourceArray))); }//ww w . j a v a2s . c om /** * 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; } 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 if (componentType.equals(Double.TYPE)) { componentType = Double.class; } int length = Array.getLength(sourceArray); Object[] targetArray = (Object[]) Array.newInstance(componentType, length); for (int ii = 0; ii < length; ii++) { targetArray[ii] = Array.get(sourceArray, ii); } return targetArray; } }