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

/**
 * Underlying implementation of add(array, index, element) methods. 
 * The last parameter is the class, which may not equal element.getClass 
 * for primitives.//from  www.  j a v  a  2  s .co  m
 *
 * @param array  the array to add the element to, may be <code>null</code>
 * @param index  the position of the new object
 * @param element  the object to add
 * @param clss the type of the element being added
 * @return A new array containing the existing elements and the new element
 */
private static Object add(Object array, int index, Object element, Class clss) {
    if (array == null) {
        if (index != 0) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
        }
        Object joinedArray = Array.newInstance(clss, 1);
        Array.set(joinedArray, 0, element);
        return joinedArray;
    }
    int length = Array.getLength(array);
    if (index > length || index < 0) {
        throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
    }
    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;
}

From source file:com.mocha.bsm.bizsm.db4otemplate.util.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 w  w .  j a  v  a2 s. co  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[array.length] = obj;
    return newArr;
}

From source file:com.datatorrent.lib.util.KryoCloneUtils.java

/**
 * Clone array of objects from source object
 * @param num size of the return array// ww  w  .  j ava  2 s  . c  om
 * @return array of T
 */
@SuppressWarnings("unchecked")
public T[] getClones(int num) {
    T[] ts = (T[]) Array.newInstance(clazz, num);
    try (Input input = new Input(bin)) {
        for (int i = 0; i < ts.length; i++) {
            input.rewind();
            ts[i] = kryo.readObject(input, clazz);
        }
    }
    return ts;
}

From source file:com.opengamma.analytics.math.curve.ObjectsCurve.java

/**
 * //from  www  .ja  va 2  s . c  o  m
 * @param data A map of <i>x-y</i> data, not null
 * @param isSorted Is the <i>x</i>-data sorted
 */
public ObjectsCurve(final Map<T, U> data, final boolean isSorted) {
    super();
    ArgumentChecker.noNulls(data.keySet(), "x values");
    ArgumentChecker.noNulls(data.values(), "y values");
    _n = data.size();
    final Map.Entry<T, U> firstEntry = data.entrySet().iterator().next();
    _xData = data.keySet().toArray((T[]) Array.newInstance(firstEntry.getKey().getClass(), 0));
    _yData = data.values().toArray((U[]) Array.newInstance(firstEntry.getValue().getClass(), 0));
    if (!isSorted) {
        ParallelArrayBinarySort.parallelBinarySort(_xData, _yData);
    }
}

From source file:fr.landel.utils.commons.CollectionUtils2.java

/**
 * To array an iterable (take the type of the first element, otherwise use
 * the default 'toArray(new T[0])'). Returns {@code null} if the iterable is
 * empty.//from  w w w.  j ava2 s.  co m
 * 
 * @param iterable
 *            The input iterable (required)
 * @param type
 *            the type of objects (optional, if null take the type of the
 *            first element)
 * @param <T>
 *            The type of object in collection
 * @return The array
 */
@SuppressWarnings("unchecked")
public static <T> T[] toArray(final Iterable<T> iterable, final Class<T> type) {
    if (!IterableUtils.isEmpty(iterable)) {
        final Iterator<T> iterator = iterable.iterator();
        final List<T> list = new ArrayList<>();
        final Set<Class<T>> classes = new HashSet<>();
        while (iterator.hasNext()) {
            final T obj = iterator.next();
            list.add(obj);
            if (obj != null) {
                classes.add(ClassUtils.getClass(obj));
            }
        }
        final Class<?> typeClass;
        if (type != null) {
            typeClass = type;
        } else if (classes.size() == 1) {
            typeClass = classes.iterator().next();
        } else {
            typeClass = Object.class;
        }
        return list.toArray((T[]) Array.newInstance(typeClass, list.size()));
    } else if (iterable != null && type != null) {
        return (T[]) Array.newInstance(type, 0);
    }
    return null;
}

From source file:FlipPolygon.java

private static <T, U> T[] copyOf(U[] arr, int newSize, Class<? extends T[]> newType) {
    T[] copy = ((Object) newType == (Object) Object[].class) ? (T[]) new Object[newSize]
            : (T[]) Array.newInstance(newType.getComponentType(), newSize);
    System.arraycopy(arr, 0, copy, 0, Math.min(arr.length, newSize));
    return copy;/*from w w w. jav  a2  s . co  m*/
}

From source file:ObjectUtils.java

/**
 * Convert the given array (which may be a primitive array) to an
 * object array (if necessary of primitive wrapper objects).
 * <p>A <code>null</code> source value will be converted to an
 * empty Object array.// ww  w . j a va 2  s.c  o m
 * @param source the (potentially primitive) array
 * @return the corresponding object array (never <code>null</code>)
 * @throws IllegalArgumentException if the parameter is not an array
 */
public static Object[] toObjectArray(Object source) {
    if (source instanceof Object[]) {
        return (Object[]) source;
    }
    if (source == null) {
        return new Object[0];
    }
    if (!source.getClass().isArray()) {
        throw new IllegalArgumentException("Source is not an array: " + source);
    }
    int length = Array.getLength(source);
    if (length == 0) {
        return new Object[0];
    }
    Class wrapperType = Array.get(source, 0).getClass();
    Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
    for (int i = 0; i < length; i++) {
        newArray[i] = Array.get(source, i);
    }
    return newArray;
}

From source file:com.laxser.blitz.lama.provider.jdbc.PreparedStatementCallbackReturnId.java

@Override
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {

    if (setter != null) {
        setter.setValues(ps);/*from w ww . jav a 2 s. co m*/
    }

    int updated = ps.executeUpdate();
    if (updated == 0) {
        if (returnType.isArray()) {
            return Array.newInstance(wrappedIdType, 0);
        } else {
            return defaultValueOf(wrappedIdType);
        }
    }

    ResultSet keys = ps.getGeneratedKeys();
    if (keys != null) {
        try {
            Object ret = null;
            if (returnType.isArray()) {
                keys.last();
                int length = keys.getRow();
                keys.beforeFirst();
                ret = Array.newInstance(wrappedIdType, length);
            }

            for (int i = 0; keys.next(); i++) {
                Object value = mapper.mapRow(keys, i);
                if (value == null && idType.isPrimitive()) {
                    // ?primitive??null??
                    value = defaultValueOf(wrappedIdType);
                }
                if (ret != null) {
                    Array.set(ret, i + 1, value);
                } else {
                    ret = value;
                    break;
                }
            }
            return ret;
        } finally {
            JdbcUtils.closeResultSet(keys);
        }
    } else {
        if (returnType.isArray()) {
            return Array.newInstance(wrappedIdType, 0);
        } else {
            return defaultValueOf(wrappedIdType);
        }
    }
}

From source file:code.elix_x.excore.utils.client.gui.elements.ListGuiElement.java

protected void reInitElements(int length) {
    this.elements = (ListGuiElement<H>.ListElement[]) Array.newInstance(ListElement.class, length);
}

From source file:com.espertech.esper.core.ResultDeliveryStrategyTypeArr.java

private Object convert(EventBean[] events) {
    if ((events == null) || (events.length == 0)) {
        return null;
    }//  w ww . j a  va  2 s.c  om

    Object array = Array.newInstance(componentType, events.length);
    int length = 0;
    for (int i = 0; i < events.length; i++) {
        if (events[i] instanceof NaturalEventBean) {
            NaturalEventBean natural = (NaturalEventBean) events[i];
            Array.set(array, length, natural.getNatural()[0]);
            length++;
        }
    }

    if (length == 0) {
        return null;
    }
    if (length != events.length) {
        Object reduced = Array.newInstance(componentType, events.length);
        System.arraycopy(array, 0, reduced, 0, length);
        array = reduced;
    }
    return array;
}