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.diversityarrays.dalclient.util.Pair.java

static public <T> Pair<T, T>[] createHomogenousPairs(Collection<T> inputs,
        Transformer<Pair<T, T>, String> joiner) {
    List<Pair<T, T>> result = new ArrayList<Pair<T, T>>();

    List<T> list = new ArrayList<T>(inputs);
    int n = list.size();
    if (n > 1) {
        for (int a = 0; a < n; ++a) {
            T aa = list.get(a);/*from   ww  w  .  ja  v  a2s.  co m*/
            for (int b = a + 1; b < n; ++b) {
                T bb = list.get(b);

                Pair<T, T> pair = new Pair<T, T>(aa, bb, null);
                String name = joiner.transform(pair);

                result.add(new Pair<T, T>(aa, bb, name));

                pair = new Pair<T, T>(bb, aa, null);
                name = joiner.transform(pair);

                result.add(new Pair<T, T>(bb, aa, name));
            }
        }
    }

    @SuppressWarnings("unchecked")
    Pair<T, T>[] pairs = (Pair<T, T>[]) Array.newInstance(Pair.class, result.size());
    pairs = result.toArray(pairs);

    return pairs;
}

From source file:GenericsUtil.java

private static Class<?> getActualClass(Type type, Map<TypeVariable<?>, Type> map) {
    if (Class.class.isInstance(type)) {
        return Class.class.cast(type);
    }/*www. j  a v  a2 s .  c  o m*/
    if (ParameterizedType.class.isInstance(type)) {
        final Type actualType = getActualType(type, map);
        return getActualClass(actualType, map);
    } else if (TypeVariable.class.isInstance(type)) {
        final Type actualType = getActualType(type, map);
        return getActualClass(actualType, map);
    } else if (GenericArrayType.class.isInstance(type)) {
        GenericArrayType genericArrayType = GenericArrayType.class.cast(type);
        final Type genericComponentType = genericArrayType.getGenericComponentType();
        Class<?> componentClass = getActualClass(genericComponentType, map);
        return Array.newInstance(componentClass, 0).getClass();
    } else {
        return null;
    }
}

From source file:ArrayUtil.java

/**
 * Copies the elements of the {@code oldArray} to a new array with extra space to 
 * append the given array {@code toAppend}.
 */// w ww  . ja  v  a2 s .  co m
@SuppressWarnings("unchecked")
public static <T> T[] append(T[] oldArray, T[] toAppend) {
    Class<?> component = oldArray.getClass().getComponentType();
    T[] array = (T[]) Array.newInstance(component, oldArray.length + toAppend.length);
    System.arraycopy(oldArray, 0, array, 0, oldArray.length);
    System.arraycopy(toAppend, 0, array, oldArray.length, toAppend.length);
    return array;
}

From source file:com.base.dao.sql.ReflectionUtils.java

public static Object convertValue(Object value, Class toType) {
    Object result = null;//from   www.j a va2  s.c  om
    if (value != null) {
        if (value.getClass().isArray() && toType.isArray()) {
            Class componentType = toType.getComponentType();
            result = Array.newInstance(componentType, Array.getLength(value));
            for (int i = 0, icount = Array.getLength(value); i < icount; i++) {
                Array.set(result, i, convertValue(Array.get(value, i), componentType));
            }
        } else {
            if ((toType == Integer.class) || (toType == Integer.TYPE))
                result = Integer.valueOf((int) longValue(value));
            if ((toType == Double.class) || (toType == Double.TYPE))
                result = new Double(doubleValue(value));
            if ((toType == Boolean.class) || (toType == Boolean.TYPE))
                result = booleanValue(value) ? Boolean.TRUE : Boolean.FALSE;
            if ((toType == Byte.class) || (toType == Byte.TYPE))
                result = Byte.valueOf((byte) longValue(value));
            if ((toType == Character.class) || (toType == Character.TYPE))
                result = new Character((char) longValue(value));
            if ((toType == Short.class) || (toType == Short.TYPE))
                result = Short.valueOf((short) longValue(value));
            if ((toType == Long.class) || (toType == Long.TYPE))
                result = Long.valueOf(longValue(value));
            if ((toType == Float.class) || (toType == Float.TYPE))
                result = new Float(doubleValue(value));
            if (toType == BigInteger.class)
                result = bigIntValue(value);
            if (toType == BigDecimal.class)
                result = bigDecValue(value);
            if (toType == String.class)
                result = stringValue(value);
            if (toType == Date.class) {
                result = DateUtils.toDate(stringValue(value));
            }
            if (Enum.class.isAssignableFrom(toType))
                result = enumValue((Class<Enum>) toType, value);
        }
    } else {
        if (toType.isPrimitive()) {
            result = primitiveDefaults.get(toType);
        }
    }
    return result;
}

From source file:ArrayGrowTest.java

/**
 * This method grows an array by allocating a new array of the same type and
 * copying all elements./*from   w  w w. jav a 2s.c o m*/
 * 
 * @param a
 *          the array to grow. This can be an object array or a primitive type
 *          array
 * @return a larger array that contains all elements of a.
 */
static Object goodArrayGrow(Object a) {
    Class cl = a.getClass();
    if (!cl.isArray())
        return null;
    Class componentType = cl.getComponentType();
    int length = Array.getLength(a);
    int newLength = length * 11 / 10 + 10;

    Object newArray = Array.newInstance(componentType, newLength);
    System.arraycopy(a, 0, newArray, 0, length);
    return newArray;
}

From source file:Main.java

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

    result[0] = single;/*from w w w .  j av a 2s . co m*/
    System.arraycopy(array, 0, result, 1, array.length);

    return result;
}

From source file:org.atemsource.atem.impl.common.attribute.collection.ArrayAttributeImpl.java

@Override
public Class<Object> getAssociationType() {
    return (Class<Object>) Array.newInstance(getTargetType().getJavaType(), 0).getClass();
}

From source file:com.microsoft.tfs.core.internal.wrappers.WrapperUtils.java

/**
 * <p>//from  w w  w  . j a  v  a 2  s .c o  m
 * Takes an array of web service objects (for example, an array of
 * {@link _Item}) and returns an array of web service wrapper objects of the
 * given type (for instance, {@link Item}).
 * </p>
 * <p>
 * A constructor for the given wrapper type that accepts one of the given
 * service objects must exist.
 * </p>
 * <p>
 * <code>null</code> values in the web service objects are copied into the
 * returned array.
 * </p>
 *
 * @param wrapperType
 *        the wrapper object class name (not array class) to use (must not
 *        be <code>null</code>)
 * @param webServiceObjects
 *        the objects to wrap (if null, null is returned)
 * @return a new array of wrapper objects, where each wraps one of the given
 *         web service objects
 */
public static Object wrap(final Class wrapperType, final Object[] webServiceObjects) {
    Check.notNull(wrapperType, "wrapperType"); //$NON-NLS-1$

    if (webServiceObjects == null) {
        return null;
    }

    final Object ret = Array.newInstance(wrapperType, webServiceObjects.length);
    Class webServiceObjectType = null;
    Constructor constructor = null;

    if (webServiceObjects.length > 0) {
        try {

            for (int i = 0; i < webServiceObjects.length; i++) {
                if (constructor == null && webServiceObjects[i] != null) {
                    webServiceObjectType = webServiceObjects[i].getClass();
                    constructor = wrapperType.getConstructor(new Class[] { webServiceObjectType });
                }

                /*
                 * Persist null values.
                 */
                Array.set(ret, i,
                        (webServiceObjects[i] != null)
                                ? constructor.newInstance(new Object[] { webServiceObjects[i] })
                                : null);
            }

        } catch (final NoSuchMethodException e) {
            final String message = MessageFormat.format(
                    "Wrapper error: the desired wrapper class {0} does not have a visible constructor that accepts the web service type {1}", //$NON-NLS-1$
                    wrapperType, webServiceObjectType);

            log.error(message, e);
            throw new RuntimeException(message);
        } catch (final Exception e) {
            final String message = MessageFormat.format("Error wrapping {0} in {1}", //$NON-NLS-1$
                    webServiceObjectType, wrapperType);

            log.error(message, e);
            throw new RuntimeException(message, e);
        }
    }

    return ret;
}

From source file:com.wcs.base.util.ArrayUtils.java

/**
 * Concatenates two arrays into one. If arr1 is null or empty, returns arr2.
 * If arr2 is null or empty, returns arr1. May return null if both arrays are null,
 * or one is empty and the other null. <br>
 * The concatenated array has componentType which is compatible with both input arrays (or Object[])
 *
 * @param arr1 input array//from   ww  w  . j  ava  2s.c om
 * @param arr2 input array
 *
 * @return Object the concatenated array, elements of arr1 first
 */
public static Object concat(Object arr1, Object arr2) {
    int len1 = (arr1 == null) ? (-1) : Array.getLength(arr1);

    if (len1 <= 0) {
        return arr2;
    }

    int len2 = (arr2 == null) ? (-1) : Array.getLength(arr2);

    if (len2 <= 0) {
        return arr1;
    }

    Class commonComponentType = commonClass(arr1.getClass().getComponentType(),
            arr2.getClass().getComponentType());
    Object newArray = Array.newInstance(commonComponentType, len1 + len2);
    System.arraycopy(arr1, 0, newArray, 0, len1);
    System.arraycopy(arr2, 0, newArray, len1, len2);

    return newArray;
}

From source file:ArrayUtils.java

public static Object[] removeFromArray(Object[] array, int i) {
    if (i < 0 || i >= array.length) {
        throw new IndexOutOfBoundsException();
    }/*  w  ww  . j  av  a 2  s . co  m*/
    Object[] newArray = (Object[]) Array.newInstance(array.getClass().getComponentType(), array.length - 1);
    System.arraycopy(array, 0, newArray, 0, i);
    System.arraycopy(array, i + 1, newArray, i, array.length - i - 1);
    return newArray;
}