Example usage for java.lang.reflect Array newInstance

List of usage examples for java.lang.reflect Array newInstance

Introduction

In this page you can find the example usage for java.lang.reflect Array newInstance.

Prototype

public static Object newInstance(Class<?> componentType, int... dimensions)
        throws IllegalArgumentException, NegativeArraySizeException 

Source Link

Document

Creates a new array with the specified component type and dimensions.

Usage

From source file:Main.java

/**
 * <p>Adds all the elements of the given arrays into a new array.</p>
 * <p>The new array contains all of the element of <code>array1</code> followed
 * by all of the elements <code>array2</code>. When an array is returned, it is always
 * a new array.</p>//from  w w w.  ja va  2 s  .c  o  m
 *
 * <pre>
 * ArrayUtils.addAll(null, null)     = null
 * ArrayUtils.addAll(array1, null)   = cloned copy of array1
 * ArrayUtils.addAll(null, array2)   = cloned copy of array2
 * ArrayUtils.addAll([], [])         = []
 * ArrayUtils.addAll([null], [null]) = [null, null]
 * ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
 * </pre>
 *
 * @param array1  the first array whose elements are added to the new array, may be <code>null</code>
 * @param array2  the second array whose elements are added to the new array, may be <code>null</code>
 * @return The new array, <code>null</code> if both arrays are <code>null</code>.
 *      The type of the new array is the type of the first array,
 *      unless the first array is null, in which case the type is the same as the second array.
 * @since 2.1
 * @throws IllegalArgumentException if the array types are incompatible
 */
public static Object[] addAll(Object[] array1, Object[] array2) {
    if (array1 == null) {
        return clone(array2);
    } else if (array2 == null) {
        return clone(array1);
    }
    Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(),
            array1.length + array2.length);
    System.arraycopy(array1, 0, joinedArray, 0, array1.length);
    try {
        System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
    } catch (ArrayStoreException ase) {
        // Check if problem was due to incompatible types
        /*
         * We do this here, rather than before the copy because:
         * - it would be a wasted check most of the time
         * - safer, in case check turns out to be too strict
         */
        final Class type1 = array1.getClass().getComponentType();
        final Class type2 = array2.getClass().getComponentType();
        if (!type1.isAssignableFrom(type2)) {
            throw new IllegalArgumentException(
                    "Cannot store " + type2.getName() + " in an array of " + type1.getName());
        }
        throw ase; // No, so rethrow original
    }
    return joinedArray;
}

From source file:legendarena.api.fanciful.ArrayWrapper.java

/**
 * Converts an iterable element collection to an array of elements.
 * The iteration order of the specified object will be used as the array element order.
 * @param list The iterable of objects which will be converted to an array.
 * @param c The type of the elements of the array.
 * @return An array of elements in the specified iterable.
 *//*from   w ww  .  ja  v a  2  s  .  c o m*/
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Iterable<? extends T> list, Class<T> c) {
    int size = -1;
    if (list instanceof Collection<?>) {
        @SuppressWarnings("rawtypes")
        Collection coll = (Collection) list;
        size = coll.size();
    }

    if (size < 0) {
        size = 0;
        //Ugly hack: Count it ourselves
        for (@SuppressWarnings("unused")
        T element : list)
            size++;
    }

    T[] result = (T[]) Array.newInstance(c, size);
    int i = 0;
    for (T element : list) // Assumes iteration order is consistent
        result[i++] = element; // Assign array element at index THEN increment counter
    return result;
}

From source file:Main.java

public static <T> T[] concat(T[] array, T single) {
    @SuppressWarnings("unchecked")
    final T[] result = (T[]) Array.newInstance(single.getClass().getComponentType(), 1 + array.length);

    System.arraycopy(array, 0, result, 0, array.length);
    result[array.length] = single;// w  w w  .j a  va 2 s. c  o m

    return result;
}

From source file:com.nfwork.dbfound.json.converter.NumberArrayConverter.java

public Object convert(Object array) {
    if (array == null) {
        return null;
    }/*from www .  j  av  a2  s.c o  m*/

    if (array.getClass().isArray()) {
        int length = Array.getLength(array);
        int dims = getDimensions(array.getClass());
        int[] dimensions = createDimensions(dims, length);
        Object result = Array.newInstance(type, dimensions);
        AbstractPrimitiveConverter converter = null;
        if (Byte.class.isAssignableFrom(type)) {
            converter = defaultValue != null && isUseDefault() ? new ByteConverter(defaultValue.byteValue())
                    : new ByteConverter();
        } else if (Short.class.isAssignableFrom(type)) {
            converter = defaultValue != null && isUseDefault() ? new ShortConverter(defaultValue.shortValue())
                    : new ShortConverter();
        } else if (Integer.class.isAssignableFrom(type)) {
            converter = defaultValue != null && isUseDefault() ? new IntConverter(defaultValue.intValue())
                    : new IntConverter();
        } else if (Long.class.isAssignableFrom(type)) {
            converter = defaultValue != null && isUseDefault() ? new LongConverter(defaultValue.longValue())
                    : new LongConverter();
        } else if (Float.class.isAssignableFrom(type)) {
            converter = defaultValue != null && isUseDefault() ? new FloatConverter(defaultValue.floatValue())
                    : new FloatConverter();
        } else if (Double.class.isAssignableFrom(type)) {
            converter = defaultValue != null && isUseDefault() ? new DoubleConverter(defaultValue.doubleValue())
                    : new DoubleConverter();
        }

        if (dims == 1) {
            for (int index = 0; index < length; index++) {
                try {
                    Object value = Array.get(array, index);
                    Object converted = MethodUtils.invokeMethod(converter, "convert", value);
                    Array.set(result, index, converted);
                } catch (Exception e) {
                    throw new ConversionException(e);
                }
            }
        } else {
            for (int index = 0; index < length; index++) {
                Array.set(result, index, convert(Array.get(array, index)));
            }
        }
        return result;
    } else {
        throw new ConversionException("argument is not an array: " + array.getClass());
    }
}

From source file:fi.foyt.foursquare.api.JSONFieldParser.java

/**
 * Static method that parses JSON "named array" into array of FoursquareEntities
 * /*from   w  ww. j a v a2  s  . c  o  m*/
 * @param clazz entity class
 * @param jsonHashList JSON "named array"
 * @param skipNonExistingFields whether parser should ignore non-existing fields
 * @return list of entities
 * @throws FoursquareApiException when something unexpected happens
 */
public static FoursquareEntity[] parseEntitiesHash(Class<?> clazz, JSONObject jsonHashList,
        boolean skipNonExistingFields) throws FoursquareApiException {
    String[] keys = getFieldNames(jsonHashList);

    FoursquareEntity[] result = (FoursquareEntity[]) Array.newInstance(clazz, keys.length);
    int i = 0;
    for (String key : keys) {
        JSONObject jsonObject;
        try {
            jsonObject = jsonHashList.getJSONObject(key);
            result[i++] = parseEntity(clazz, jsonObject, skipNonExistingFields);
        } catch (JSONException e) {
            throw new FoursquareApiException(e);
        }
    }

    return result;
}

From source file:net.navasoft.madcoin.backend.services.vo.response.impl.AppCategoriesSuccessResponseVO.java

/**
 * Sets the business lines./*from   w  w w  . jav a2s.c o m*/
 * 
 * @param existentBusinessLines
 *            the new business lines
 * @since 24/08/2014, 06:05:43 PM
 */
@Override
public void setBusinessLines(BusinessLines... existentBusinessLines) {
    lob = (BusinessLines[]) Array.newInstance(BusinessLines.class, 0);
    lob = (BusinessLines[]) ArrayUtils.add(lob, existentBusinessLines[0]);
}

From source file:Main.java

/**
 * <p>Adds all the elements of the given arrays into a new array.</p>
 * <p>The new array contains all of the element of <code>array1</code> followed
 * by all of the elements <code>array2</code>. When an array is returned, it is always
 * a new array.</p>/*  w  w w  . ja  v a2  s. co  m*/
 *
 * <pre>
 * ArrayUtils.addAll(null, null)     = null
 * ArrayUtils.addAll(array1, null)   = cloned copy of array1
 * ArrayUtils.addAll(null, array2)   = cloned copy of array2
 * ArrayUtils.addAll([], [])         = []
 * ArrayUtils.addAll([null], [null]) = [null, null]
 * ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
 * </pre>
 *
 * @param array1  the first array whose elements are added to the new array, may be <code>null</code>
 * @param array2  the second array whose elements are added to the new array, may be <code>null</code>
 * @return The new array, <code>null</code> if <code>null</code> array inputs. 
 *      The type of the new array is the type of the first array.
 * @since 2.1
 */
public static Object[] addAll(Object[] array1, Object[] array2) {
    if (array1 == null) {
        return clone(array2);
    } else if (array2 == null) {
        return clone(array1);
    }
    Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(),
            array1.length + array2.length);
    System.arraycopy(array1, 0, joinedArray, 0, array1.length);
    System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
    return joinedArray;
}

From source file:Main.java

/**
 * Resizes an array.//from   w  w  w  . j a v  a 2 s.c  o m
 */
public static <T> T[] resize(T[] buffer, int newSize) {
    Class<T> componentType = (Class<T>) buffer.getClass().getComponentType();
    T[] temp = (T[]) Array.newInstance(componentType, newSize);
    System.arraycopy(buffer, 0, temp, 0, buffer.length >= newSize ? newSize : buffer.length);
    return temp;
}

From source file:Main.java

/**
 * <p>Adds all the elements of the given arrays into a new array.</p>
 * <p>The new array contains all of the element of {@code array1} followed
 * by all of the elements {@code array2}. When an array is returned, it is always
 * a new array.</p>/*w  w  w  .ja va  2s  .c o m*/
 *
 * <pre>
 * ArrayUtils.addAll(null, null)     = null
 * ArrayUtils.addAll(array1, null)   = cloned copy of array1
 * ArrayUtils.addAll(null, array2)   = cloned copy of array2
 * ArrayUtils.addAll([], [])         = []
 * ArrayUtils.addAll([null], [null]) = [null, null]
 * ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
 * </pre>
 *
 * @param <T> the component type of the array
 * @param array1  the first array whose elements are added to the new array, may be {@code null}
 * @param array2  the second array whose elements are added to the new array, may be {@code null}
 * @return The new array, {@code null} if both arrays are {@code null}.
 *      The type of the new array is the type of the first array,
 *      unless the first array is null, in which case the type is the same as the second array.
 * @since 2.1
 * @throws IllegalArgumentException if the array types are incompatible
 */
public static <T> T[] addAll(T[] array1, T... array2) {
    if (array1 == null) {
        return clone(array2);
    } else if (array2 == null) {
        return clone(array1);
    }
    final Class<?> type1 = array1.getClass().getComponentType();
    @SuppressWarnings("unchecked")
    // OK, because array is of type T
    T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
    System.arraycopy(array1, 0, joinedArray, 0, array1.length);
    try {
        System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
    } catch (ArrayStoreException ase) {
        // Check if problem was due to incompatible types
        /*
         * We do this here, rather than before the copy because:
         * - it would be a wasted check most of the time
         * - safer, in case check turns out to be too strict
         */
        final Class<?> type2 = array2.getClass().getComponentType();
        if (!type1.isAssignableFrom(type2)) {
            throw new IllegalArgumentException(
                    "Cannot store " + type2.getName() + " in an array of " + type1.getName(), ase);
        }
        throw ase; // No, so rethrow original
    }
    return joinedArray;
}

From source file:Main.java

public static <T> T[] remove(final T[] array, final int from, final int to) {
    assert (to >= from) : to + " - " + from;
    int length = getLength(array);
    if (from < 0 || to >= length) {
        throw new IndexOutOfBoundsException("from: " + from + ", to: " + to + ", Length: " + length);
    }/*from  w  w w .  j a v a 2  s .  co  m*/
    int remsize = to - from + 1;
    Object result = Array.newInstance(array.getClass().getComponentType(), length - remsize);
    System.arraycopy(array, 0, result, 0, from);
    if (to < length - 1) {
        System.arraycopy(array, to + 1, result, from, length - to - 1);
    }
    return (T[]) result;
}