private static Object add(final Object array,final int index,final Object element,final Class<?> clss){
  if (array == null) {
    if (index != 0) {
      throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
    }
    final Object joinedArray=Array.newInstance(clss,1);
    Array.set(joinedArray,0,element);
    return joinedArray;
  }
  final int length=Array.getLength(array);
  if (index > length || index < 0) {
    throw new IndexOutOfBoundsException("Index: " + index + ", Length: "+ length);
  }
  final Object result=Array.newInstance(clss,length + 1);
  System.arraycopy(array,0,result,0,index);
  Array.set(result,index,element);
  if (index < length) {
    System.arraycopy(array,index,result,index + 1,length - index);
  }
  return result;
}

private static Object add ( final Object array , final int index , final Object element , final Class < ? > clss ) { if ( array == null ) { if ( index != 0 ) { throw new IndexOutOfBoundsException ( "Index: " + index + ", Length: 0" ) ; } final Object joinedArray = Array . newInstance ( clss , 1 ) ; Array . set ( joinedArray , 0 , element ) ; return joinedArray ; } final int length = Array . getLength ( array ) ; if ( index > length || index < 0 ) { throw new IndexOutOfBoundsException ( "Index: " + index + ", Length: " + length ) ; } final Object result = Array . newInstance ( clss , length + 1 ) ; System . arraycopy ( array , 0 , result , 0 , index ) ; Array . set ( result , index , element ) ; if ( index < length ) { System . arraycopy ( array , index , result , index + 1 , length - index ) ; } return result ; }
underlying implementation of add ( array , index , element ) methods . the last parameter is the class , which may not equal element . getclass for primitives .
