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:IteratorUtils.java

/**
 * @param null_terminate iff there is extra space in the array, set the element
 *        immediately after the last from the iterator to null.
 *//*from w w w .  ja  v  a2s  . c o  m*/
public static Object[] toArray(Iterator ii, int array_size, Class componentClass, boolean null_terminate) {
    Object[] out = (Object[]) Array.newInstance(componentClass, array_size);
    fillArray(ii, out, null_terminate);
    return out;
}

From source file:com.adobe.acs.tools.csv.impl.Column.java

public T[] getMultiData(String data) {
    final String[] vals = StringUtils.split(data, this.multiDelimiter);

    final List<T> list = new ArrayList<T>();

    for (String val : vals) {
        T obj = (T) this.toObjectType(val, this.getDataType());
        list.add(obj);//from w w  w.j a va 2 s.c o  m
    }

    return list.toArray((T[]) Array.newInstance((this.getDataType()), 0));
}

From source file:com.discovery.darchrow.lang.ArrayUtil.java

/**
 *  <code>componentType</code> ?  <code>length</code>.
 * /*  w  w  w. j a  v a  2s . c o m*/
 * <h3>:</h3>
 * 
 * <blockquote>
 * 
 * <pre class="code">
 * assertArrayEquals(new Integer[] {}, ArrayUtil.newArray(Integer.class, 0));
 * assertArrayEquals(new Integer[] { null, null, null }, ArrayUtil.newArray(Integer.class, 3));
 * </pre>
 * 
 * </blockquote>
 *
 * @param <T>
 *            the generic type
 * @param componentType
 *            the component type
 * @param length
 *            the length of the new array
 * @return  <code>componentType</code> null, {@link NullPointerException}<br>
 *          {@code length < 0} , {@link IllegalArgumentException}<br>
 * @see java.lang.reflect.Array#newInstance(Class, int)
 * @see java.lang.reflect.Array#newInstance(Class, int...)
 * @see "com.google.common.collect#newArray(Class, int)"
 * @since 1.6.1
 */
@SuppressWarnings("unchecked")
public static <T> T[] newArray(Class<T> componentType, int length) {
    Validate.notNull(componentType, "componentType can't be null!");
    Validate.isTrue(length >= 0, "length:[%s],must >=0", length);
    return (T[]) Array.newInstance(componentType, length);
}

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

/**
 * Formulate tips.//w  w  w  .  j  a v a  2s .c  o m
 * 
 * @return the string[]
 * @since 24/08/2014, 07:46:29 PM
 */
@Override
public String[] formulateTips() {
    String[] finalTips = (String[]) Array.newInstance(String.class, 0);
    if (allowedTipsQuantity != -1) {
        for (int availableTip = 1; availableTip < allowedTipsQuantity + 1; availableTip++) {
            finalTips = (String[]) ArrayUtils.add(finalTips,
                    tips.getMessage(MessageFormat.format(locatedMessage + tipSuffix, availableTip),
                            new Object[] { availableTip }, "", language));
        }
    } // Add the filter chain or REGEXP case handling, if applies.
    return finalTips;
}

From source file:de.bund.bva.pliscommon.serviceapi.core.serviceimpl.MappingHelper.java

/**
 * Bildet ein Objekt mithilfe von Dozer auf einen gewnschten Zieltyp ab. Im Gegensatz zu
 * {@link Mapper#map(Object, Class)} knnen als Zieltyp auch generische Collections, String und primitive
 * Typen bergeben werden.//www.j a  va 2s.c o  m
 * 
 * @param mapper
 *            der Dozer-Mapper
 * @param source
 *            das zu mappende Objekt
 * @param destinationType
 *            der Zieltyp
 * @return das gemappte Objekt
 */
@SuppressWarnings("unchecked")
public static Object map(Mapper mapper, Object source, Type destinationType) {
    if (source == null) {
        return null;
    }

    if (destinationType instanceof ParameterizedType) {
        ParameterizedType parDestinationType = (ParameterizedType) destinationType;

        Class<?> rawClass = (Class<?>) parDestinationType.getRawType();
        if (List.class.isAssignableFrom(rawClass)) {
            return mapCollection(mapper, source, parDestinationType, new ArrayList<Object>());
        } else if (SortedSet.class.isAssignableFrom(rawClass)) {
            return mapCollection(mapper, source, parDestinationType, new TreeSet<Object>());
        } else if (Set.class.isAssignableFrom(rawClass)) {
            return mapCollection(mapper, source, parDestinationType, new HashSet<Object>());
        } else if (SortedMap.class.isAssignableFrom(rawClass)) {
            return mapMap(mapper, source, parDestinationType, new TreeMap<Object, Object>());
        } else if (Map.class.isAssignableFrom(rawClass)) {
            return mapMap(mapper, source, parDestinationType, new HashMap<Object, Object>());
        }

        destinationType = parDestinationType.getRawType();
    }

    if (destinationType instanceof GenericArrayType) {
        if (!source.getClass().isArray()) {
            throw new IllegalArgumentException("Ein Mapping auf den Array-Typ " + destinationType
                    + " wird nicht untersttzt, wenn das Quellobjekt kein Array ist. Typ des Quellobjekts: "
                    + source.getClass());
        }

        // wir werden im Array Element pro Element mappen
        Type elementType = ((GenericArrayType) destinationType).getGenericComponentType();
        Object[] sourceArray = (Object[]) source;
        Object[] destinationArray = (Object[]) Array.newInstance((Class<?>) elementType, sourceArray.length);
        for (int i = 0; i < sourceArray.length; i++) {
            destinationArray[i] = MappingHelper.map(mapper, sourceArray[i], elementType);
        }
        return destinationArray;
    } else if ((destinationType instanceof Class<?>) && ((Class<?>) destinationType).isArray()) {
        if (!source.getClass().isArray()) {
            throw new IllegalArgumentException("Ein Mapping auf den Array-Typ " + destinationType
                    + " wird nicht untersttzt, wenn das Quellobjekt kein Array ist. Typ des Quellobjekts: "
                    + source.getClass());
        }
        Class<?> destinationTypeClass = (Class<?>) destinationType;
        // wir werden im Array Element pro Element mappen
        Type elementType = destinationTypeClass.getComponentType();
        Object[] sourceArray = (Object[]) source;
        Object[] destinationArray = (Object[]) Array.newInstance((Class<?>) elementType, sourceArray.length);
        for (int i = 0; i < sourceArray.length; i++) {
            destinationArray[i] = MappingHelper.map(mapper, sourceArray[i], elementType);
        }
        return destinationArray;
    }

    if (!(destinationType instanceof Class<?>)) {
        throw new IllegalArgumentException(
                "Ein Mapping auf Typ " + destinationType + " wird nicht untersttzt");
    }

    Class<?> destinationClass = (Class<?>) destinationType;

    if (ClassUtils.isPrimitiveOrWrapper(destinationClass) || MAPPING_BLACKLIST.contains(destinationClass)) {
        return source;
    } else if (destinationClass.isEnum()) {
        // wir mssen auf dieser Ebene Enums leider manuell mappen
        if (!(source instanceof Enum)) {
            throw new IllegalArgumentException("Ein Mapping auf ein Enum " + destinationClass
                    + " wird nicht untersttzt, da das Quellobjekt kein Enumobjekt ist (Quellobjektstyp: "
                    + source.getClass().toString() + ").");
        }
        return Enum.valueOf((Class<Enum>) destinationClass, ((Enum<?>) source).name());
    } else {
        return mapper.map(source, destinationClass);
    }
}

From source file:ch.systemsx.cisd.openbis.generic.server.authorization.DefaultReturnValueFilter.java

private final static <T> T[] proceedArray(final PersonPE person, final Method method,
        final IValidator<T> validator, final T[] returnValue) {
    if (returnValue.length == 0) {
        return returnValue;
    }//from  w w  w .j  a v a  2 s  . c  o m
    final List<T> list = FilteredList.decorate(returnValue, new ValidatorAdapter<T>(validator, person));
    final T[] array = castToArray(Array.newInstance(returnValue.getClass().getComponentType(), list.size()));
    final T[] newValue = castToArray(list.toArray(array));
    int diff = returnValue.length - newValue.length;
    if (diff > 0) {
        operationLog.info(String.format(FILTER_APPLIED_ON_ARRAY, MethodUtils.describeMethod(method), diff));
    }
    return newValue;
}

From source file:com.xpfriend.fixture.cast.temp.ObjectOperatorBase.java

private Object toArrayInternal(Class<?> componentType, String textValue) {
    String[] textValues = textValue.split("\\|");
    if (String.class.equals(componentType)) {
        return textValues;
    }//w  w  w .  j a  v a2  s  .c  o  m

    Object values = Array.newInstance(componentType, textValues.length);
    for (int i = 0; i < Array.getLength(values); i++) {
        Array.set(values, i, TypeConverter.changeType(textValues[i], componentType));
    }
    return values;
}

From source file:com.astamuse.asta4d.data.DefaultContextDataFinder.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/* www . j a v a 2 s .  co m*/
public ContextDataHolder findDataInContext(Context context, String scope, String name, Class<?> targetType)
        throws DataOperationException {
    ContextDataHolder dataHolder = findByType(context, scope, name, targetType);

    if (dataHolder != null) {
        return dataHolder;
    }

    if (StringUtils.isEmpty(scope)) {
        dataHolder = findDataByScopeOrder(context, 0, name);
    } else {
        dataHolder = context.getDataHolder(scope, name);
    }

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

    Object foundData = dataHolder.getValue();
    Object transformedData = null;
    UnsupportedValueException usve = null;

    Class<?> srcType = new TypeInfo(foundData.getClass()).getType();
    if (targetType.isAssignableFrom(srcType)) {
        transformedData = foundData;
    } else if (srcType.isArray() && targetType.isAssignableFrom(srcType.getComponentType())) {
        transformedData = Array.get(foundData, 0);
    } else if (targetType.isArray() && targetType.getComponentType().isAssignableFrom(srcType)) {
        Object array = Array.newInstance(srcType, 1);
        Array.set(array, 0, foundData);
        transformedData = array;
    } else {
        try {
            transformedData = Configuration.getConfiguration().getDataTypeTransformer().transform(srcType,
                    targetType, foundData);
        } catch (UnsupportedValueException ex) {
            usve = ex;
        }
    }
    if (usve == null) {
        dataHolder.setData(dataHolder.getName(), dataHolder.getScope(), foundData, transformedData);
    } else {
        dataHolder.setData(dataHolder.getName(), InjectUtil.ContextDataTypeUnMatchScope, foundData,
                transformedData);
    }
    return dataHolder;
}

From source file:egovframework.rte.itl.webservice.service.impl.MessageConverterImpl.java

@SuppressWarnings("unchecked")
public Object convertToValueObject(Object source, Type type)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
    LOG.debug("convertToValueObject(source = " + source + ", type = " + type + ")");

    if (type instanceof PrimitiveType) {
        LOG.debug("Type is a Primitive Type");
        return source;
    } else if (type instanceof ListType) {
        LOG.debug("Type is a List Type");

        ListType listType = (ListType) type;
        Object[] components = ((Collection<?>) source).toArray();

        Class<?> arrayClass = classLoader.loadClass(listType);
        Object array = Array.newInstance(arrayClass.getComponentType(), components.length);

        for (int i = 0; i < components.length; i++) {
            Array.set(array, i, convertToValueObject(components[i], listType.getElementType()));
        }// w w w.j a va  2  s.  c o  m
        return array;
    } else if (type instanceof RecordType) {
        LOG.debug("Type is a Record(Map) Type");

        RecordType recordType = (RecordType) type;
        Map<String, Object> map = (Map<String, Object>) source;

        Class<?> recordClass = classLoader.loadClass(recordType);
        Object record = recordClass.newInstance();

        for (Entry<String, Object> entry : map.entrySet()) {
            Object fieldValue = convertToValueObject(entry.getValue(), recordType.getFieldType(entry.getKey()));
            recordClass.getField(entry.getKey()).set(record, fieldValue);
        }
        return record;
    }
    LOG.error("Type is invalid");
    throw new InstantiationException();
}

From source file:com.g3net.tool.CollectionUtils.java

public static Map<Object, Object[]> mergeMapIntoGivenMap(Map givenMap, Map map) {
    Set keys = givenMap.keySet();

    Map<Object, Object[]> newMap = new HashMap<Object, Object[]>();
    for (Object key : keys) {
        Object value = givenMap.get(key);
        if (value == null)
            continue;
        if (value.getClass().isArray()) {
            Object[] objs = ObjectUtils.toObjectArray(value);
            newMap.put(key, objs);//from  www.j  a  v  a 2s. co  m
        } else {
            Object[] newArray = (Object[]) Array.newInstance(value.getClass(), 1);
            Array.set(newArray, 0, value);
            newMap.put(key, newArray);
        }
    }

    keys = map.keySet();
    for (Object key : keys) {
        Object value = map.get(key);
        if (value == null)
            continue;
        if (value.getClass().isArray()) {
            Object[] objs = ObjectUtils.toObjectArray(value);
            Object[] old = newMap.get(key);
            if (old != null) {
                Object[] newObjs = (Object[]) ArrayUtils.append(old, objs);
                newMap.put(key, newObjs);
            } else {
                newMap.put(key, objs);
            }

        } else {
            Object[] newArray = (Object[]) Array.newInstance(value.getClass(), 1);
            Array.set(newArray, 0, value);
            Object[] old = newMap.get(key);
            if (old != null) {
                Object[] newObjs = (Object[]) ArrayUtils.append(old, newArray);
                newMap.put(key, newObjs);
            } else {
                newMap.put(key, newArray);
            }
        }
    }

    return newMap;
}