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:ArrayUtils.java

/**
 * Inserts an element into the array--for primitive types
 * // ww  w .  j av a 2s.co m
 * @param anArray
 *            The array to insert into
 * @param anElement
 *            The element to insert
 * @param anIndex
 *            The index for the new element
 * @return The new array with all elements of <code>anArray</code>, but with
 *         <code>anElement</code> inserted at index <code>anIndex</code>
 */
public static Object addP(Object anArray, Object anElement, int anIndex) {
    Object ret;
    int length;
    if (anArray == null) {
        if (anIndex != 0)
            throw new ArrayIndexOutOfBoundsException("Cannot set " + anIndex + " element in a null array");
        ret = Array.newInstance(anElement.getClass(), 1);
        Array.set(ret, 0, anElement);
        return ret;
    } else {
        length = Array.getLength(anArray);
        ret = Array.newInstance(anArray.getClass().getComponentType(), length + 1);
    }
    System.arraycopy(anArray, 0, ret, 0, anIndex);
    put(ret, anElement, anIndex);
    System.arraycopy(anArray, anIndex, ret, anIndex + 1, length - anIndex);
    return ret;
}

From source file:com.britesnow.snow.util.ObjectUtil.java

/**
 * <div class="notes"> <strong>Notes:</strong>
 * <ul>//from  w  ww .  j  a  v  a  2s.c om
 * <li>So far does not safeguard any type conversion (will throw an runtime exception if parsing fail)</li>
 * </ul>
 * </div>
 * 
 * @param <T>
 * @param values
 *            String arrays of the value to be converted
 * @param cls
 * @param defaultValues
 * @return The typed array given a value of the String.
 */
public static final <T> T getValue(String[] values, Class<T> cls, T defaultValues) {
    if (values != null && cls.isArray()) {
        Class compCls = cls.getComponentType();
        T resultArray = (T) Array.newInstance(compCls, values.length);
        int i = 0;
        for (String v : values) {
            Object r = getValue(v, compCls, null);
            Array.set(resultArray, i++, r);
        }
        return resultArray;
    } else {
        return defaultValues;
    }

}

From source file:com.fengduo.bee.commons.component.ObjectArrayDataBinder.java

@SuppressWarnings("unchecked")
public static <E> E[] createArray(Class<E> clazz, int capacity) {
    E[] array = (E[]) Array.newInstance(clazz, capacity);
    for (int i = 0; i < capacity; i++) {
        try {/*from  w  w w .  j  a  v  a 2s . com*/
            array[i] = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    return array;
}

From source file:Main.java

/**
 * <p>Produces a new array containing the elements between
 * the start and end indices.</p>/*from   ww  w.  j  a  v a 2s.c o m*/
 *
 * <p>The start index is inclusive, the end index exclusive.
 * Null array input produces null output.</p>
 *
 * <p>The component type of the subarray is always the same as
 * that of the input array. Thus, if the input is an array of type
 * {@code Date}, the following usage is envisaged:</p>
 *
 * <pre>
 * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);
 * </pre>
 *
 * @param <T> the component type of the array
 * @param array  the array
 * @param startIndexInclusive  the starting index. Undervalue (&lt;0)
 *      is promoted to 0, overvalue (&gt;array.length) results
 *      in an empty array.
 * @param endIndexExclusive  elements up to endIndex-1 are present in the
 *      returned subarray. Undervalue (&lt; startIndex) produces
 *      empty array, overvalue (&gt;array.length) is demoted to
 *      array length.
 * @return a new array containing the elements between
 *      the start and end indices.
 * @since 2.1
 */
public static <T> T[] subarray(T[] array, int startIndexInclusive, int endIndexExclusive) {
    if (array == null) {
        return null;
    }
    if (startIndexInclusive < 0) {
        startIndexInclusive = 0;
    }
    if (endIndexExclusive > array.length) {
        endIndexExclusive = array.length;
    }
    int newSize = endIndexExclusive - startIndexInclusive;
    Class<?> type = array.getClass().getComponentType();
    if (newSize <= 0) {
        @SuppressWarnings("unchecked")
        // OK, because array is of type T
        final T[] emptyArray = (T[]) Array.newInstance(type, 0);
        return emptyArray;
    }
    @SuppressWarnings("unchecked")
    // OK, because array is of type T
    T[] subarray = (T[]) Array.newInstance(type, newSize);
    System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
    return subarray;
}

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

/**
 * Gets the causes.//from  ww  w.  j  ava 2s . c o  m
 * 
 * @return the causes
 * @since 24/08/2014, 08:10:23 PM
 */
@Override
@JsonIgnore
public Object[] getCauses() {
    Object[] causes = (Object[]) Array.newInstance(Object.class, 0);
    causes = ArrayUtils.add(causes, lob);
    return causes;
}

From source file:Main.java

/**
 * Convert a given String into the appropriate Class.
 * /*from  www .  j a  va2 s .  c  o m*/
 * @param name
 *          Name of class
 * @param cl
 *          ClassLoader to use
 * 
 * @return The class for the given name
 * 
 * @throws ClassNotFoundException
 *           When the class could not be found by the specified ClassLoader
 */
private final static Class convertToJavaClass(String name, ClassLoader cl) throws ClassNotFoundException {
    int arraySize = 0;
    while (name.endsWith("[]")) {
        name = name.substring(0, name.length() - 2);
        arraySize++;
    }

    // Check for a primitive type
    Class c = (Class) PRIMITIVE_NAME_TYPE_MAP.get(name);

    if (c == null) {
        // No primitive, try to load it from the given ClassLoader
        try {
            c = cl.loadClass(name);
        } catch (ClassNotFoundException cnfe) {
            throw new ClassNotFoundException("Parameter class not found: " + name);
        }
    }

    // if we have an array get the array class
    if (arraySize > 0) {
        int[] dims = new int[arraySize];
        for (int i = 0; i < arraySize; i++) {
            dims[i] = 1;
        }
        c = Array.newInstance(c, dims).getClass();
    }

    return c;
}

From source file:Main.java

/**
 * <p>Produces a new array containing the elements between
 * the start and end indices.</p>/*from   www .java  2  s  .  c  o  m*/
 *
 * <p>The start index is inclusive, the end index exclusive.
 * Null array input produces null output.</p>
 *
 * <p>The component type of the subarray is always the same as
 * that of the input array. Thus, if the input is an array of type
 * {@code Date}, the following usage is envisaged:</p>
 *
 * <pre>
 * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);
 * </pre>
 *
 * @param <T> the component type of the array
 * @param array  the array
 * @param startIndexInclusive  the starting index. Undervalue (&lt;0)
 *      is promoted to 0, overvalue (&gt;array.length) results
 *      in an empty array.
 * @param endIndexExclusive  elements up to endIndex-1 are present in the
 *      returned subarray. Undervalue (&lt; startIndex) produces
 *      empty array, overvalue (&gt;array.length) is demoted to
 *      array length.
 * @return a new array containing the elements between
 *      the start and end indices.
 * @since 2.1
 * @see Arrays#copyOfRange(Object[], int, int)
 */
public static <T> T[] subarray(final T[] array, int startIndexInclusive, int endIndexExclusive) {
    if (array == null) {
        return null;
    }
    if (startIndexInclusive < 0) {
        startIndexInclusive = 0;
    }
    if (endIndexExclusive > array.length) {
        endIndexExclusive = array.length;
    }
    final int newSize = endIndexExclusive - startIndexInclusive;
    final Class<?> type = array.getClass().getComponentType();
    if (newSize <= 0) {
        @SuppressWarnings("unchecked")
        // OK, because array is of type T
        final T[] emptyArray = (T[]) Array.newInstance(type, 0);
        return emptyArray;
    }
    @SuppressWarnings("unchecked")
    // OK, because array is of type T
    final T[] subarray = (T[]) Array.newInstance(type, newSize);
    System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
    return subarray;
}

From source file:net.navasoft.madcoin.backend.services.rest.impl.BusinessService.java

/**
 * Gets the business lines.//  w  ww. j  a va 2  s . c  om
 * 
 * @return the business lines
 * @since 21/08/2014, 11:56:35 PM
 */
@Override
public SuccessResponseVO getBusinessLines() {
    BusinessSuccessResponseVO response = new AppBusinessLinesSuccessResponseVO();
    List<BusinessLines> total = dao.getAll();
    if (!total.isEmpty()) {
        BusinessLines[] totalLOB = (BusinessLines[]) Array.newInstance(BusinessLines.class, total.size());
        response.setBusinessLines(total.toArray(totalLOB));
        return response;
    } else {
        throw ControllerExceptionFactory.createException(InsufficientLOBException.class.getCanonicalName(), 1);
    }
}

From source file:net.navasoft.madcoin.backend.services.rest.impl.NotificationMaster.java

/**
 * Distribute./*from  ww w  . ja v a2s .  co  m*/
 * 
 * @throws Exception
 *             the exception
 * @since 3/09/2014, 11:35:49 PM
 */
@Override
public void distribute() throws Exception {
    int slaveTimes = getStrategy().getRate().getWorkerLoad().intValue();
    int carga = getStrategy().getRate().getTotalLoad().intValue();
    Provider[] total;
    try {
        total = (Provider[]) Array.newInstance(getParameterizedType(), 0);
        total = population.toArray(total);
        for (int i = 0; i < total.length;) {
            for (int j = 0; j < slaveTimes; j++) {
                slaves.add((Slave<Provider, ?>) createBlankSlave());
            }
            i = i + carga;
            // total = (Oficina[])ArrayUtils.remove(total, i);
        }
        int k = 0;
        for (Slave<Provider, ?> worker : slaves) {
            prepareSlave(worker);
            putLoad(worker, total[k]);
            k++;
        }
    } catch (NegativeArraySizeException | ClassNotFoundException e) {
        journal.error(e);
    }
}

From source file:com.vk.sdk.util.VKJsonHelper.java

public static Object toArray(JSONArray array, Class arrayClass) {
    Object ret = Array.newInstance(arrayClass.getComponentType(), array.length());
    Class<?> subType = arrayClass.getComponentType();

    for (int i = 0; i < array.length(); i++) {
        try {/*  ww  w . j a  va2 s . c o  m*/
            Object jsonItem = array.get(i);
            Object objItem = subType.newInstance();
            if (jsonItem instanceof JSONObject) {
                JSONObject jsonItem2 = (JSONObject) jsonItem;
                if (objItem instanceof VKApiModel) {
                    VKApiModel objItem2 = (VKApiModel) objItem;
                    ((VKApiModel) objItem).parse(jsonItem2);
                    Array.set(ret, i, objItem2);
                }
            }
        } catch (JSONException e) {
            if (VKSdk.DEBUG)
                e.printStackTrace();
        } catch (InstantiationException e) {
            if (VKSdk.DEBUG)
                e.printStackTrace();
        } catch (IllegalAccessException e) {
            if (VKSdk.DEBUG)
                e.printStackTrace();
        }
    }
    return ret;
}