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

/**
 * <p>Inserts the specified element at the specified position in the array. 
 * Shifts the element currently at that position (if any) and any subsequent
 * elements to the right (adds one to their indices).</p>
 *
 * <p>This method returns a new array with the same elements of the input
 * array plus the given element on the specified position. The component 
 * type of the returned array is always the same as that of the input 
 * array.</p>/*www.  jav  a  2 s  .  co m*/
 *
 * <p>If the input array is <code>null</code>, a new one element array is returned
 *  whose component type is the same as the element.</p>
 * 
 * <pre>
 * ArrayUtils.insert(null, 0, null)      = [null]
 * ArrayUtils.insert(null, 0, "a")       = ["a"]
 * ArrayUtils.insert(["a"], 1, null)     = ["a", null]
 * ArrayUtils.insert(["a"], 1, "b")      = ["a", "b"]
 * ArrayUtils.insert(["a", "b"], 3, "c") = ["a", "b", "c"]
 * </pre>
 * 
 * @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
 * @return A new array containing the existing elements and the new element
 * @throws IndexOutOfBoundsException if the index is out of range 
 * (index < 0 || index > array.length).
 */
@SuppressWarnings("unchecked")
public static <T> T[] insert(final Object array, final int index, final Object element) {
    if (array == null) {
        if (index != 0) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
        }
        Object joinedArray = Array.newInstance(element != null ? element.getClass() : Object.class, 1);
        Array.set(joinedArray, 0, element);
        return (T[]) joinedArray;
    }
    int length = getLength(array);
    if (index > length || index < 0) {
        throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
    }
    Object result = Array.newInstance(array.getClass().getComponentType(), 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 (T[]) result;
}

From source file:com.google.feedserver.util.BeanUtil.java

/**
 * Applies a collection of properties to a JavaBean. Converts String and
 * String[] values to correct property types
 * /*from  ww w  .j a  v a  2s  . c o m*/
 * @param properties A map of the properties to set on the JavaBean
 * @param bean The JavaBean to set the properties on
 */
public void convertPropertiesToBean(Map<String, Object> properties, Object bean) throws IntrospectionException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException, ParseException {
    BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
    for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) {
        String name = p.getName();
        Object value = properties.get(name);
        Method reader = p.getReadMethod();
        Method writer = p.getWriteMethod();
        // we only care about "complete" properties
        if (reader != null && writer != null && value != null) {
            Class<?> propertyType = writer.getParameterTypes()[0];
            if (isBean(propertyType)) {
                // this is a bean
                if (propertyType.isArray()) {
                    propertyType = propertyType.getComponentType();
                    Object beanArray = Array.newInstance(propertyType, 1);

                    if (value.getClass().isArray()) {
                        Object[] valueArrary = (Object[]) value;
                        int length = valueArrary.length;
                        beanArray = Array.newInstance(propertyType, length);
                        for (int index = 0; index < valueArrary.length; ++index) {
                            Object valueObject = valueArrary[index];
                            fillBeanInArray(propertyType, beanArray, index, valueObject);
                        }
                    } else {
                        fillBeanInArray(propertyType, beanArray, 0, value);
                    }
                    value = beanArray;
                } else if (propertyType == Timestamp.class) {
                    value = new Timestamp(TIMESTAMP_FORMAT.parse((String) value).getTime());
                } else {
                    Object beanObject = createBeanObject(propertyType, value);
                    value = beanObject;
                }
            } else {
                Class<?> valueType = value.getClass();
                if (!propertyType.isAssignableFrom(valueType)) {
                    // convert string input values to property type
                    try {
                        if (valueType == String.class) {
                            value = ConvertUtils.convert((String) value, propertyType);
                        } else if (valueType == String[].class) {
                            value = ConvertUtils.convert((String[]) value, propertyType);
                        } else if (valueType == Object[].class) {
                            // best effort conversion
                            Object[] objectValues = (Object[]) value;
                            String[] stringValues = new String[objectValues.length];
                            for (int i = 0; i < objectValues.length; i++) {
                                stringValues[i] = objectValues[i] == null ? null : objectValues[i].toString();
                            }
                            value = ConvertUtils.convert(stringValues, propertyType);
                        } else {
                        }
                    } catch (ConversionException e) {
                        throw new IllegalArgumentException(
                                "Conversion failed for " + "property '" + name + "' with value '" + value + "'",
                                e);
                    }
                }
            }
            // We only write values that are present in the map. This allows
            // defaults or previously set values in the bean to be retained.
            writer.invoke(bean, value);
        }
    }
}

From source file:com.github.michalbednarski.intentslab.Utils.java

public static Object[] deepCastArray(Object[] array, Class targetType) {
    assert targetType.isArray() && !targetType.getComponentType().isPrimitive();

    if (targetType.isInstance(array) || array == null) {
        return array;
    }//w w  w. jav  a 2  s . c  o m

    Class componentType = targetType.getComponentType();
    Class nestedComponentType = componentType.getComponentType();
    Object[] newArray = (Object[]) Array.newInstance(componentType, array.length);
    if (nestedComponentType != null && !nestedComponentType.isPrimitive()) {
        for (int i = 0; i < array.length; i++) {
            newArray[i] = deepCastArray((Object[]) array[i], nestedComponentType);
        }
    } else {
        System.arraycopy(array, 0, newArray, 0, array.length);
    }
    return newArray;
}

From source file:com.creactiviti.piper.core.MapObject.java

@Override
public <T> T[] getArray(Object aKey, Class<T> aElementType) {
    Object value = get(aKey);//  w ww  . ja  va2 s .  c o m
    if (value.getClass().isArray() && value.getClass().getComponentType().equals(aElementType)) {
        return (T[]) value;
    }
    List<T> list = getList(aKey, aElementType);
    T[] toR = (T[]) Array.newInstance(aElementType, list.size());
    for (int i = 0; i < list.size(); i++) {
        toR[i] = list.get(i);
    }
    return toR;
}

From source file:org.nabucco.alfresco.enhScriptEnv.common.script.converter.general.ArrayConverter.java

protected Object convertToArray(final Object value, final ValueConverter globalDelegate,
        final Class<?> expectedClass, final boolean toScript) {
    final Object result;
    final Class<?> valueClass = value.getClass();
    if (valueClass.isArray()) {
        final Object arr = Array.newInstance(expectedClass.getComponentType(), Array.getLength(value));

        for (int idx = 0; idx < Array.getLength(value); idx++) {
            final Object converted = toScript
                    ? globalDelegate.convertValueForScript(Array.get(value, idx),
                            expectedClass.getComponentType())
                    : globalDelegate.convertValueForJava(Array.get(value, idx),
                            expectedClass.getComponentType());
            Array.set(arr, idx, converted);
        }// w  w  w  .  j  a v a 2 s .  co  m
        result = arr;
    } else {
        final Collection<?> coll;
        if (value instanceof Collection<?>) {
            coll = (Collection<?>) value;
        } else {
            final List<Object> list = new ArrayList<Object>();
            final Iterator<?> it = (Iterator<?>) value;
            while (it.hasNext()) {
                list.add(it.next());
            }
            coll = list;
        }

        final Object arr = Array.newInstance(expectedClass.getComponentType(), coll.size());
        final Iterator<?> it = coll.iterator();
        for (int idx = 0; it.hasNext(); idx++) {
            final Object converted = toScript
                    ? globalDelegate.convertValueForScript(it.next(), expectedClass.getComponentType())
                    : globalDelegate.convertValueForJava(it.next(), expectedClass.getComponentType());
            Array.set(arr, idx, converted);
        }
        result = arr;
    }
    return result;
}

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

/**
 * //www . j a va2s. c  o m
 * @param data A set of <i>x-y</i> pairs, not null
 * @param isSorted Is the <i>x</i>-data sorted
 * @param name The name of the curve
 */
public ObjectsCurve(final Set<Pair<T, U>> data, final boolean isSorted, final String name) {
    super(name);
    ArgumentChecker.notNull(data, "data");
    _n = data.size();
    final List<T> xTemp = new ArrayList<>(_n);
    final List<U> yTemp = new ArrayList<>(_n);
    final int i = 0;
    for (final Pair<T, U> entry : data) {
        ArgumentChecker.notNull(entry, "element " + i + " of data");
        xTemp.add(entry.getFirst());
        yTemp.add(entry.getSecond());
    }
    final Pair<T, U> firstEntry = data.iterator().next();
    _xData = xTemp.toArray((T[]) Array.newInstance(firstEntry.getFirst().getClass(), 0));
    _yData = yTemp.toArray((U[]) Array.newInstance(firstEntry.getSecond().getClass(), 0));
    if (!isSorted) {
        ParallelArrayBinarySort.parallelBinarySort(_xData, _yData);
    }
}

From source file:de.yaio.services.webshot.server.controller.WebshotProvider.java

private static <T> T[] concatenate(T[] a, T[] b) {
    int aLen = a.length;
    int bLen = b.length;

    @SuppressWarnings("unchecked")
    T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
    System.arraycopy(a, 0, c, 0, aLen);
    System.arraycopy(b, 0, c, aLen, bLen);

    return c;//from   ww w  . j  av a 2 s.  c  o  m
}

From source file:com.googlecode.jsfFlex.myFaces.ClassUtils.java

/**
 * Similar as {@link #classForName(String)}, but also supports primitive types
 * and arrays as specified for the JavaType element in the JavaServer Faces Config DTD.
 *
 * @param type fully qualified class name or name of a primitive type, both optionally
 *             followed by "[]" to indicate an array type
 * @return the corresponding Class//  ww w  . j a v  a 2s.co  m
 * @throws NullPointerException if type is null
 * @throws ClassNotFoundException
 */
public static Class javaTypeToClass(String type) throws ClassNotFoundException {
    if (type == null)
        throw new NullPointerException("type");

    // try common types and arrays of common types first
    Class clazz = (Class) COMMON_TYPES.get(type);
    if (clazz != null) {
        return clazz;
    }

    int len = type.length();
    if (len > 2 && type.charAt(len - 1) == ']' && type.charAt(len - 2) == '[') {
        String componentType = type.substring(0, len - 2);
        Class componentTypeClass = classForName(componentType);
        return Array.newInstance(componentTypeClass, 0).getClass();
    } else {
        return classForName(type);
    }
}

From source file:org.jodah.typetools.TypeResolver.java

/**
 * Resolves the raw class for the {@code genericType}, using the type variable information from the {@code subType}
 * else {@link Unknown} if the raw class cannot be resolved.
 * //from   ww  w .j  a  v  a  2  s .  co  m
 * @param type
 *            to resolve raw class for
 * @param subType
 *            to extract type variable information from
 * @return raw class for the {@code genericType} else {@link Unknown} if it cannot be resolved
 */
public static Class<?> resolveRawClass(Type genericType, Class<?> subType) {
    if (genericType instanceof Class) {
        return (Class<?>) genericType;
    } else if (genericType instanceof ParameterizedType) {
        return resolveRawClass(((ParameterizedType) genericType).getRawType(), subType);
    } else if (genericType instanceof GenericArrayType) {
        GenericArrayType arrayType = (GenericArrayType) genericType;
        Class<?> compoment = resolveRawClass(arrayType.getGenericComponentType(), subType);
        return Array.newInstance(compoment, 0).getClass();
    } else if (genericType instanceof TypeVariable) {
        TypeVariable<?> variable = (TypeVariable<?>) genericType;
        genericType = getTypeVariableMap(subType).get(variable);
        genericType = genericType == null ? resolveBound(variable) : resolveRawClass(genericType, subType);
    }

    return genericType instanceof Class ? (Class<?>) genericType : Unknown.class;
}

From source file:org.jsonschema2pojo.integration.json.JsonTypesIT.java

@Test
public void arrayItemsAreRecursivelyMerged() throws Exception {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/json/complexPropertiesInArrayItem.json",
            "com.example", config("sourceType", "json"));
    Class<?> genType = resultsClassLoader.loadClass("com.example.ComplexPropertiesInArrayItem");
    Class<?> listItemType = resultsClassLoader.loadClass("com.example.List");
    Class<?> objItemType = resultsClassLoader.loadClass("com.example.Obj");

    Object[] items = (Object[]) OBJECT_MAPPER.readValue(
            this.getClass().getResourceAsStream("/json/complexPropertiesInArrayItem.json"),
            Array.newInstance(genType, 0).getClass());
    {/*from  www  . jav  a2 s.co m*/
        Object item = items[0];

        List<?> itemList = (List<?>) genType.getMethod("getList").invoke(item);
        assertThat((Integer) listItemType.getMethod("getA").invoke(itemList.get(0)), is(1));
        assertThat((String) listItemType.getMethod("getC").invoke(itemList.get(0)), is("hey"));
        assertNull(listItemType.getMethod("getB").invoke(itemList.get(0)));

        Object itemObj = genType.getMethod("getObj").invoke(item);
        assertThat((String) objItemType.getMethod("getName").invoke(itemObj), is("k"));
        assertNull(objItemType.getMethod("getIndex").invoke(itemObj));
    }
    {
        Object item = items[1];

        List<?> itemList = (List<?>) genType.getMethod("getList").invoke(item);
        assertThat((Integer) listItemType.getMethod("getB").invoke(itemList.get(0)), is(177));
        assertThat((String) listItemType.getMethod("getC").invoke(itemList.get(0)), is("hey again"));
        assertNull(listItemType.getMethod("getA").invoke(itemList.get(0)));

        Object itemObj = genType.getMethod("getObj").invoke(item);
        assertThat((Integer) objItemType.getMethod("getIndex").invoke(itemObj), is(8));
        assertNull(objItemType.getMethod("getName").invoke(itemObj));
    }
}