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:gov.redhawk.model.sca.impl.ScaSimpleSequencePropertyImpl.java

/**
 * <!-- begin-user-doc -->//from w  w w  . j  a  v a2  s.  c  om
 * @since 13.0
 * <!-- end-user-doc -->
 * @generated NOT
 */
@Override
public Object[] getValue() {
    // END GENERATED CODE
    Class<?> type = Object.class;
    if (getDefinition() != null) {
        EDataType dataType = getDefinition().getType().toEDataType(getDefinition().isComplex());
        type = dataType.getInstanceClass();
    }
    return getValues().toArray((Object[]) Array.newInstance(type, getValues().size()));
    // BEGIN GENERATED CODE
}

From source file:com.evolveum.midpoint.util.ReflectionUtil.java

public static Object invokeMethod(Object object, String methodName, List<?> argList)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    Method method = findMethod(object, methodName, argList);
    if (method == null) {
        throw new NoSuchMethodException(
                "No method " + methodName + " for arguments " + debugDumpArgList(argList) + " in " + object);
    }/* w ww.  j a v  a 2 s . c o m*/
    Object[] args = argList.toArray();
    if (method.isVarArgs()) {
        Class<?> parameterTypeClass = method.getParameterTypes()[0];
        Object[] varArgs = (Object[]) Array.newInstance(parameterTypeClass.getComponentType(), args.length);
        for (int i = 0; i < args.length; i++) {
            varArgs[i] = args[i];
        }
        args = new Object[] { varArgs };
    }
    try {
        return method.invoke(object, args);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(
                e.getMessage() + " for arguments " + debugDumpArgList(argList) + " in " + object, e);
    }
}

From source file:antre.TypeResolver.java

/**
 * Resolves the raw class for the given {@code genericType}, using the type variable information
 * from the {@code targetType}.//from  ww w.j a v  a2s  . co m
 */
public static Class<?> resolveClass(Type genericType, Class<?> targetType) {
    if (genericType instanceof Class) {
        return (Class<?>) genericType;
    } else if (genericType instanceof ParameterizedType) {
        return resolveClass(((ParameterizedType) genericType).getRawType(), targetType);
    } else if (genericType instanceof GenericArrayType) {
        GenericArrayType arrayType = (GenericArrayType) genericType;
        Class<?> compoment = resolveClass(arrayType.getGenericComponentType(), targetType);
        return Array.newInstance(compoment, 0).getClass();
    } else if (genericType instanceof TypeVariable) {
        TypeVariable<?> variable = (TypeVariable<?>) genericType;
        genericType = getTypeVariableMap(targetType).get(variable);
        genericType = genericType == null ? resolveBound(variable) : resolveClass(genericType, targetType);
    }

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

From source file:ArraysX.java

/**
 * Duplicates the specified array./*from  ww  w .j  a  va 2  s  . c  o m*/
 *
 * <p>The array could be an array of objects or primiitives.
 *
 * @param ary the array
 * @param jb the beginning index (included)
 * @param je the ending index (excluded)
 * @return an array duplicated from ary
 * @exception IllegalArgumentException if ary is not any array
 * @exception IndexOutOfBoundsException if out of bounds
 */
public static final Object duplicate(Object ary, int jb, int je) {
    int len = Array.getLength(ary);
    if (jb < 0 || je > len || jb > je)
        throw new IndexOutOfBoundsException(jb + " or " + je + " exceeds " + len);

    len = je - jb;
    Object dst = Array.newInstance(ary.getClass().getComponentType(), len);
    System.arraycopy(ary, jb, dst, 0, len);
    return dst;
}

From source file:de.pribluda.android.jsonmarshaller.JSONUnmarshaller.java

/**
 * recursively populate array out of hierarchy of JSON Objects
 *
 * @param arrayClass original array class
 * @param json      json object in question
 * @return/*from ww  w.j av a 2  s . c o m*/
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object populateRecursive(Class arrayClass, Object json) throws JSONException,
        InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
    if (arrayClass.isArray() && json instanceof JSONArray) {
        final int length = ((JSONArray) json).length();
        final Class componentType = arrayClass.getComponentType();
        Object retval = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Array.set(retval, i, populateRecursive(componentType, ((JSONArray) json).get(i)));
        }
        return retval;
    } else {
        // this is leaf object, JSON needs to be unmarshalled,
        if (json instanceof JSONObject) {
            return unmarshall((JSONObject) json, arrayClass);
        } else {
            // while all others can be returned verbatim
            return json;
        }
    }
}

From source file:fi.foyt.foursquare.api.JSONFieldParser.java

/**
 * Parses single JSON object field into a value. Value might be of type String, Integer, Long, Double, Boolean or FoursquareEntity depending classes field type
 * //w w  w  .  ja va 2 s . co  m
 * @param clazz class
 * @param jsonObject JSON Object
 * @param objectFieldName field to be parsed
 * @param skipNonExistingFields whether parser should ignore non-existing fields
 * @return field's value
 * @throws JSONException when JSON parsing error occures
 * @throws FoursquareApiException when something unexpected happens
 */
private static Object parseValue(Class<?> clazz, JSONObject jsonObject, String objectFieldName,
        boolean skipNonExistingFields) throws JSONException, FoursquareApiException {
    if (clazz.isArray()) {
        Object value = jsonObject.get(objectFieldName);

        JSONArray jsonArray;
        if (value instanceof JSONArray) {
            jsonArray = (JSONArray) value;
        } else {
            if ((value instanceof JSONObject) && (((JSONObject) value).has("items"))) {
                jsonArray = ((JSONObject) value).getJSONArray("items");
            } else {
                throw new FoursquareApiException("JSONObject[\"" + objectFieldName
                        + "\"] is neither a JSONArray nor a {count, items} object.");
            }
        }

        Class<?> arrayClass = clazz.getComponentType();
        Object[] arrayValue = (Object[]) Array.newInstance(arrayClass, jsonArray.length());

        for (int i = 0, l = jsonArray.length(); i < l; i++) {
            if (arrayClass.equals(String.class)) {
                arrayValue[i] = jsonArray.getString(i);
            } else if (arrayClass.equals(Integer.class)) {
                arrayValue[i] = jsonArray.getInt(i);
            } else if (arrayClass.equals(Long.class)) {
                arrayValue[i] = jsonArray.getLong(i);
            } else if (arrayClass.equals(Double.class)) {
                arrayValue[i] = jsonArray.getDouble(i);
            } else if (arrayClass.equals(Boolean.class)) {
                arrayValue[i] = jsonArray.getBoolean(i);
            } else if (isFoursquareEntity(arrayClass)) {
                arrayValue[i] = parseEntity(arrayClass, jsonArray.getJSONObject(i), skipNonExistingFields);
            } else {
                throw new FoursquareApiException("Unknown array type: " + arrayClass);
            }
        }

        return arrayValue;
    } else if (clazz.equals(String.class)) {
        return jsonObject.getString(objectFieldName);
    } else if (clazz.equals(Integer.class)) {
        return jsonObject.getInt(objectFieldName);
    } else if (clazz.equals(Long.class)) {
        return jsonObject.getLong(objectFieldName);
    } else if (clazz.equals(Double.class)) {
        return jsonObject.getDouble(objectFieldName);
    } else if (clazz.equals(Boolean.class)) {
        return jsonObject.getBoolean(objectFieldName);
    } else if (isFoursquareEntity(clazz)) {
        return parseEntity(clazz, jsonObject.getJSONObject(objectFieldName), skipNonExistingFields);
    } else {
        throw new FoursquareApiException("Unknown type: " + clazz);
    }
}

From source file:es.caib.zkib.jxpath.util.BasicTypeConverter.java

/**
 * Converts the supplied object to the specified
 * type. Throws a runtime exception if the conversion is
 * not possible./*from   ww w  .ja  v  a  2  s  .  c o  m*/
 * @param object to convert
 * @param toType destination class
 * @return converted object
 */
public Object convert(Object object, final Class toType) {
    if (object == null) {
        return toType.isPrimitive() ? convertNullToPrimitive(toType) : null;
    }

    if (toType == Object.class) {
        if (object instanceof NodeSet) {
            return convert(((NodeSet) object).getValues(), toType);
        }
        if (object instanceof Pointer) {
            return convert(((Pointer) object).getValue(), toType);
        }
        return object;
    }
    final Class useType = TypeUtils.wrapPrimitive(toType);
    Class fromType = object.getClass();

    if (useType.isAssignableFrom(fromType)) {
        return object;
    }

    if (fromType.isArray()) {
        int length = Array.getLength(object);
        if (useType.isArray()) {
            Class cType = useType.getComponentType();

            Object array = Array.newInstance(cType, length);
            for (int i = 0; i < length; i++) {
                Object value = Array.get(object, i);
                Array.set(array, i, convert(value, cType));
            }
            return array;
        }
        if (Collection.class.isAssignableFrom(useType)) {
            Collection collection = allocateCollection(useType);
            for (int i = 0; i < length; i++) {
                collection.add(Array.get(object, i));
            }
            return unmodifiableCollection(collection);
        }
        if (length > 0) {
            Object value = Array.get(object, 0);
            return convert(value, useType);
        }
        return convert("", useType);
    }
    if (object instanceof Collection) {
        int length = ((Collection) object).size();
        if (useType.isArray()) {
            Class cType = useType.getComponentType();
            Object array = Array.newInstance(cType, length);
            Iterator it = ((Collection) object).iterator();
            for (int i = 0; i < length; i++) {
                Object value = it.next();
                Array.set(array, i, convert(value, cType));
            }
            return array;
        }
        if (Collection.class.isAssignableFrom(useType)) {
            Collection collection = allocateCollection(useType);
            collection.addAll((Collection) object);
            return unmodifiableCollection(collection);
        }
        if (length > 0) {
            Object value;
            if (object instanceof List) {
                value = ((List) object).get(0);
            } else {
                Iterator it = ((Collection) object).iterator();
                value = it.next();
            }
            return convert(value, useType);
        }
        return convert("", useType);
    }
    if (object instanceof NodeSet) {
        return convert(((NodeSet) object).getValues(), useType);
    }
    if (object instanceof Pointer) {
        return convert(((Pointer) object).getValue(), useType);
    }
    if (useType == String.class) {
        return object.toString();
    }
    if (object instanceof Boolean) {
        if (Number.class.isAssignableFrom(useType)) {
            return allocateNumber(useType, ((Boolean) object).booleanValue() ? 1 : 0);
        }
        if ("java.util.concurrent.atomic.AtomicBoolean".equals(useType.getName())) {
            try {
                return useType.getConstructor(new Class[] { boolean.class })
                        .newInstance(new Object[] { object });
            } catch (Exception e) {
                throw new JXPathTypeConversionException(useType.getName(), e);
            }
        }
    }
    if (object instanceof Number) {
        double value = ((Number) object).doubleValue();
        if (useType == Boolean.class) {
            return value == 0.0 ? Boolean.FALSE : Boolean.TRUE;
        }
        if (Number.class.isAssignableFrom(useType)) {
            return allocateNumber(useType, value);
        }
    }
    if (object instanceof String) {
        Object value = convertStringToPrimitive(object, useType);
        if (value != null || "".equals(object)) {
            return value;
        }
    }

    Converter converter = ConvertUtils.lookup(useType);
    if (converter != null) {
        return converter.convert(useType, object);
    }

    throw new JXPathTypeConversionException("Cannot convert " + object.getClass() + " to " + useType);
}

From source file:com.feilong.commons.core.util.CollectionsUtil.java

/**
 * ??<br>//from   ww w .  ja v a  2  s .c  o m
 * note:T , ??,???null.
 * 
 * @param <T>
 *            the generic type
 * @param collection
 *            collection
 * @return ,if Validator.isNullOrEmpty(collection),return null
 * @throws IllegalArgumentException
 *             list isNullOrEmpty
 * @see java.lang.reflect.Array#newInstance(Class, int)
 * @see java.lang.reflect.Array#newInstance(Class, int...)
 * @see java.util.Collection#toArray()
 * @see java.util.Collection#toArray(Object[])
 * @see java.util.List#toArray()
 * @see java.util.List#toArray(Object[])
 * @see java.util.Vector#toArray()
 * @see java.util.Vector#toArray(Object[])
 * @see java.util.LinkedList#toArray()
 * @see java.util.LinkedList#toArray(Object[])
 * @see java.util.ArrayList#toArray()
 * @see java.util.ArrayList#toArray(Object[])
 */
public static <T> T[] toArray(Collection<T> collection) throws IllegalArgumentException {
    if (Validator.isNullOrEmpty(collection)) {
        return null;
    }

    //**********************************************************************
    Iterator<T> iterator = collection.iterator();

    T firstT = iterator.next();
    //list.get(0);
    //TODO ??
    if (Validator.isNullOrEmpty(firstT)) {
        throw new IllegalArgumentException("list's first item can't be null/empty!");
    }
    //**********************************************************************
    Class<?> compontType = firstT.getClass();

    int size = collection.size();

    @SuppressWarnings("unchecked")
    T[] tArray = (T[]) Array.newInstance(compontType, size);

    // alength0,???API??size,?.
    // ?alengthCollectionsize????API?.

    //?toArray(new Object[0])  toArray() ?. 
    return collection.toArray(tArray);
}

From source file:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Remove the index'th element from the supplied collection.
 * @param collection to edit/*  w  w w  . j  a  v a2  s  .c om*/
 * @param index int
 * @return the resulting collection
 */
public static Object remove(Object collection, int index) {
    collection = getValue(collection);
    if (collection == null) {
        return null;
    }
    if (index >= getLength(collection)) {
        throw new JXPathException("No such element at index " + index);
    }
    if (collection.getClass().isArray()) {
        int length = Array.getLength(collection);
        Object smaller = Array.newInstance(collection.getClass().getComponentType(), length - 1);
        if (index > 0) {
            System.arraycopy(collection, 0, smaller, 0, index);
        }
        if (index < length - 1) {
            System.arraycopy(collection, index + 1, smaller, index, length - index - 1);
        }
        return smaller;
    }
    if (collection instanceof List) {
        int size = ((List) collection).size();
        if (index < size) {
            ((List) collection).remove(index);
        }
        return collection;
    }
    if (collection instanceof Collection) {
        Iterator it = ((Collection) collection).iterator();
        for (int i = 0; i < index; i++) {
            if (!it.hasNext()) {
                break;
            }
            it.next();
        }
        if (it.hasNext()) {
            it.next();
            it.remove();
        }
        return collection;
    }
    throw new JXPathException("Cannot remove " + collection.getClass().getName() + "[" + index + "]");
}