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:com.testtubebaby.artemismain.core.ComponentManager.java

void plugSystemsData(SystemsData sysData) {
    compData = sysData.getCompData();/* w w w  .j a v  a 2  s . c o m*/

    int numOfComp = compData.getNumOfComp();
    compTable = new Component[numOfComp][];

    for (int i = 0; i < numOfComp; i++) {
        compTable[i] = (Component[]) Array.newInstance(compData.indToComp(i), world.getMaximumEntityCount());
    }

    compPools = compData.getCompPools();
}

From source file:Main.java

/**
 * Returns a new array with a single element appended at the end.
 *  Use this sparingly, for it will allocate a new array.  You can
 *  easily turn a linear-time algorithm to quadratic this way.
 * @param v Original array//w w w. ja  v  a 2 s  .  co m
 * @param elem Element to add to end
 * @return Array with length v+1 that is (v0,v1,...,vn,elem).
 *  Runtime type will be same as he pased-in array.
 */
public static Object[] append(Object[] v, Object elem) {
    Object[] ret = (Object[]) Array.newInstance(v.getClass().getComponentType(), v.length + 1);
    System.arraycopy(v, 0, ret, 0, v.length);
    ret[v.length] = elem;
    return ret;
}

From source file:com.liferay.wsrp.proxy.TypeConvertorUtil.java

public static Object convert(Object source, int sourceVersion) throws Exception {

    if (source == null) {
        return null;
    }//from w w  w .  j  a v a 2s  .  co  m

    String sourcePackage = _V1_PACKAGE;
    String destinationPackage = _V2_PACKAGE;

    if (sourceVersion == 2) {
        sourcePackage = _V2_PACKAGE;
        destinationPackage = _V1_PACKAGE;
    }

    Class<?> sourceClass = source.getClass();

    String sourceClassName = sourceClass.getSimpleName();

    Object destination = null;

    if (sourceClass.isArray()) {
        destination = source;

        Class<?> componentType = sourceClass.getComponentType();

        if (componentType.getName().contains(sourcePackage)) {
            Object[] sourceArray = (Object[]) source;

            Class<?> destinationComponentType = Class
                    .forName(destinationPackage + componentType.getSimpleName());

            Object[] destinationArray = (Object[]) Array.newInstance(destinationComponentType,
                    sourceArray.length);

            for (int i = 0; i < sourceArray.length; i++) {
                Object sourceArrayValue = sourceArray[i];

                destinationArray[i] = convert(sourceArrayValue, sourceVersion);
            }

            destination = destinationArray;
        }
    } else if (sourceClass == CookieProtocol.class) {
        CookieProtocol cookieProtocol = (CookieProtocol) source;

        destination = oasis.names.tc.wsrp.v2.types.CookieProtocol.fromValue(cookieProtocol.getValue());
    } else if (sourceClass == oasis.names.tc.wsrp.v2.types.CookieProtocol.class) {

        oasis.names.tc.wsrp.v2.types.CookieProtocol cookieProtocol = (oasis.names.tc.wsrp.v2.types.CookieProtocol) source;

        destination = CookieProtocol.fromValue(cookieProtocol.getValue());
    } else if (sourceClass == StateChange.class) {
        StateChange stateChange = (StateChange) source;

        destination = oasis.names.tc.wsrp.v2.types.StateChange.fromValue(stateChange.getValue());
    } else if (sourceClass == oasis.names.tc.wsrp.v2.types.StateChange.class) {

        oasis.names.tc.wsrp.v2.types.StateChange stateChange = (oasis.names.tc.wsrp.v2.types.StateChange) source;

        destination = StateChange.fromValue(stateChange.getValue());
    } else {
        Class<?> destinationClass = Class.forName(destinationPackage + sourceClassName);

        destination = destinationClass.newInstance();

        Map<String, Object> sourceChildren = PropertyUtils.describe(source);

        for (Map.Entry<String, Object> sourceChildEntry : sourceChildren.entrySet()) {

            String sourceChildName = sourceChildEntry.getKey();

            if (sourceChildName.equals("class")) {
                continue;
            }

            Object sourceChild = sourceChildEntry.getValue();

            if (sourceChild == null) {
                continue;
            }

            _convert(sourceVersion, sourcePackage, sourceClass, sourceChild, sourceChildName, destination);
        }
    }

    return destination;
}

From source file:com.l2jfree.util.AbstractBunch.java

@Override
public <T> T[] moveToArray(Class<T> clazz) {
    return moveToArray((T[]) Array.newInstance(clazz, size()));
}

From source file:ArrayHelper.java

/**
 * Concatenates the given arrays into a single long array.
 * The returned array will be of the common super type of the
 * two given arrays.//from   ww w  .j ava 2 s. c  o m
 * <p>
 * For example it can be called like this:<br>
 * <pre>
 * String[] arr = (String[])ArrayHelper.cat(new String[]{"one","two"}, new String[]{"three","four"});
 * </pre>
 *
 * @param arr1 first array
 * @param arr2 second array
 * @return an array whose length is the sum of the given array's lengths and contains all the elements in the given arrays.
 * @since ostermillerutils 1.06.00
 */
public static Object[] cat(Object[] arr1, Object[] arr2) {
    // Use reflection to find the super class of both arrays
    Class<?> commonSuperClass = Object.class;
    boolean foundcommonSuperClass = false;
    for (Class<?> c1 = arr1.getClass().getComponentType(); !foundcommonSuperClass
            && !c1.equals(Object.class); c1 = c1.getSuperclass()) {
        for (Class<?> c2 = arr2.getClass().getComponentType(); !foundcommonSuperClass
                && !c2.equals(Object.class); c2 = c2.getSuperclass()) {
            if (c2.equals(c1)) {
                foundcommonSuperClass = true;
                commonSuperClass = c1;
            }
        }
    }
    // Create a new array of the correct type
    Object[] result = (Object[]) Array.newInstance(commonSuperClass, arr1.length + arr2.length);
    // Copy the two arrays into the large array
    System.arraycopy(arr1, 0, result, 0, arr1.length);
    System.arraycopy(arr2, 0, result, arr1.length, arr2.length);
    return result;
}

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>//from w w  w .j  ava  2s.  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 <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(final T[] array1, final 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
    final 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 (final 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:ObjectUtils.java

/**
 * Append the given Object to the given array, returning a new array
 * consisting of the input array contents plus the given Object.
 * @param array the array to append to (can be <code>null</code>)
 * @param obj the Object to append/*from   w  ww. ja  v a 2  s.c o m*/
 * @return the new array (of the same component type; never <code>null</code>)
 */
public static Object[] addObjectToArray(Object[] array, Object obj) {
    Class compType = Object.class;
    if (array != null) {
        compType = array.getClass().getComponentType();
    } else if (obj != null) {
        compType = obj.getClass();
    }
    int newArrLength = (array != null ? array.length + 1 : 1);
    Object[] newArr = (Object[]) Array.newInstance(compType, newArrLength);
    if (array != null) {
        System.arraycopy(array, 0, newArr, 0, array.length);
    }
    newArr[newArr.length - 1] = obj;
    return newArr;
}

From source file:net.dv8tion.jda.core.utils.cache.impl.AbstractCacheView.java

@SuppressWarnings("unchecked")
protected AbstractCacheView(Class<T> type, Function<T, String> nameMapper) {
    this.nameMapper = nameMapper;
    this.type = type;
    this.emptyArray = (T[]) Array.newInstance(type, 0);
}

From source file:at.diamonddogs.util.Utils.java

/**
 * Returns an array/*from w  w w. jav  a 2  s .  co  m*/
 *
 * @param <T>    generic type of the items to place into an array
 * @param clazz  the class of generic type <T>
 * @param values an arbitrary number of values
 * @return an array containing all values passed to this method
 * @deprecated do not use this method, the implementation doesn't make a lot
 * of sense and furthermore, the whole method is somewhat
 * pointless.
 */
@Deprecated
public static <T> T[] asArray(Class<T> clazz, T... values) {
    @SuppressWarnings("unchecked")
    T[] array = (T[]) Array.newInstance(clazz, values.length);
    for (int i = 0; i < values.length; i++) {
        array[i] = values[i];
    }
    return array;
}

From source file:net.navasoft.madcoin.backend.services.controller.exception.ControllerException.java

/**
 * Literal.//  w ww .  jav a2s  .  co  m
 * 
 * @param genericReplacements
 *            the generic replacements
 * @return the string[]
 * @since 24/08/2014, 08:21:59 PM
 */
protected static String[] literal(Object[] genericReplacements) {
    String[] results = (String[]) Array.newInstance(String.class, 0);
    for (Object translated : genericReplacements) {
        if (translated instanceof UserTypes) {
            results = (String[]) ArrayUtils.add(results, ((UserTypes) translated).getExternalValue().name());
        } else if (translated instanceof Integer) {
        } else {
            results = (String[]) ArrayUtils.add(results, translated.toString());
        }
    }
    return results;
}