Advertisement
MrFrAnTA

Generic wrapper of primitive arrays

Feb 8th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.15 KB | None | 0 0
  1.   public static Object[] toObjectArray(Object obj) {
  2.     if (obj == null) {
  3.       return null;
  4.     }
  5.  
  6.     // get class type of argument
  7.     Class<?> clazz = obj.getClass();
  8.     Preconditions.checkArgument(clazz.isArray(), "Given object is not array!");
  9.  
  10.     // get length of array
  11.     int length = Array.getLength(obj);
  12.  
  13.     // prepare class type of
  14.     Class<?> componentType = clazz.getComponentType();
  15.  
  16.     // check whatever the array is array of primitives
  17.     if (!componentType.isPrimitive()) {
  18.       // return original argument
  19.       return (Object[])obj;
  20.     }
  21.     // prepare Object variant of component type
  22.     Class<?> componentObjectType = PrimitiveUtils.wrap(componentType);
  23.  
  24.     // prepare array
  25.     Object[] array = (Object[])Array.newInstance(componentObjectType, length);
  26.     for (int i = 0; i < length; i++) {
  27.       // boxing
  28.       try {
  29.         Constructor<?> construct = componentObjectType.getConstructor(componentType);
  30.         array[i] = construct.newInstance(Array.get(obj, i));
  31.       }
  32.       catch (Exception exc) {
  33.         // this should not happen
  34.         exc.printStackTrace();
  35.       }
  36.     }
  37.  
  38.     return array;
  39.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement