Example usage for java.lang.reflect Array set

List of usage examples for java.lang.reflect Array set

Introduction

In this page you can find the example usage for java.lang.reflect Array set.

Prototype

public static native void set(Object array, int index, Object value)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

Source Link

Document

Sets the value of the indexed component of the specified array object to the specified new value.

Usage

From source file:com.jilk.ros.rosbridge.implementation.JSON.java

private static Object convertJSONArrayToArray(JSONArray ja, Class c, Registry<Class> r) {
    Object result = Array.newInstance(c, ja.size());
    for (int i = 0; i < ja.size(); i++) {
        Object lookup = ja.get(i);
        Object value = null;//  w  w w .j ava 2 s  . c  om
        if (lookup != null) {
            if (lookup.getClass().equals(JSONObject.class))
                value = convertJSONObjectToMessage((JSONObject) lookup, c, r);
            else if (lookup.getClass().equals(JSONArray.class)) // this is not actually allowed in ROS
                value = convertJSONArrayToArray((JSONArray) lookup, c.getComponentType(), r);
            else
                value = convertJSONPrimitiveToPrimitive(lookup, c);
            Array.set(result, i, value);
        }
    }

    return result;
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

private Object doConvertToArray(Map<String, Object> context, Object o, Member member, String s, Object value,
        Class toType) {/*www  .j a  va 2s.c  om*/
    Object result = null;
    Class componentType = toType.getComponentType();

    if (componentType != null) {
        TypeConverter converter = getTypeConverter(context);

        if (value.getClass().isArray()) {
            int length = Array.getLength(value);
            result = Array.newInstance(componentType, length);

            for (int i = 0; i < length; i++) {
                Object valueItem = Array.get(value, i);
                Array.set(result, i, converter.convertValue(context, o, member, s, valueItem, componentType));
            }
        } else {
            result = Array.newInstance(componentType, 1);
            Array.set(result, 0, converter.convertValue(context, o, member, s, value, componentType));
        }
    }

    return result;
}

From source file:com.sun.faces.el.PropertyResolverImpl.java

public void setValue(Object base, int index, Object value) {

    if (base == null) {
        throw new PropertyNotFoundException("Error setting index '" + index + "' in bean of type null");
    }//ww w  .  j  a  v  a  2  s.com

    try {
        if (base.getClass().isArray()) {
            Array.set(base, index, value);
        } else if (base instanceof List) {
            ((List) base).set(index, value);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("setValue:Error setting index:" + index);
            }
            throw new EvaluationException(
                    "Bean of type " + base.getClass().getName() + " doesn't have indexed properties");
        }
    } catch (IndexOutOfBoundsException e) {
        throw new PropertyNotFoundException("Error setting index " + index, e);
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.debug("setValue:Error setting index:" + index);
        }
        throw new EvaluationException("Error setting index " + index, t);
    }

}

From source file:org.primeframework.mvc.parameter.convert.AbstractAnnotationConverter.java

/**
 * This performs the conversion from an array of String values to an array of the given type.
 *
 * @param annotation        The annotation from the field.
 * @param values            The values to convert to an array.
 * @param convertTo         The array type to convert to.
 * @param dynamicAttributes The dynamic attributes to assist in the conversion.
 * @param expression        The full path to the expression that is causing the conversion.
 * @return The converted value.//w ww  .jav a 2s.  c  o  m
 * @throws ConversionException     If the conversion failed.
 * @throws ConverterStateException if the converter didn't have all of the information it needed to perform the
 *                                 conversion.
 */
protected Object stringsToArray(T annotation, String[] values, Type convertTo,
        Map<String, String> dynamicAttributes, String expression) throws ConversionException {
    if (values == null) {
        return null;
    }

    Object finalArray;
    Class<?> rawType = TypeTools.rawType(convertTo);
    if (values.length == 0) {
        finalArray = Array.newInstance(rawType.getComponentType(), 0);
    } else {
        finalArray = Array.newInstance(rawType.getComponentType(), values.length);
        for (int i = 0; i < values.length; i++) {
            Object singleValue = stringToObject(annotation, values[i], rawType.getComponentType(),
                    dynamicAttributes, expression);
            Array.set(finalArray, i, singleValue);
        }
    }

    return finalArray;
}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java

/**
 * Given an object extracted from JSONObject field, convert it to an
 * appropriate object with type appropriate for given type so that it can be
 * assigned to the associated field of the ummarshalled object. eg.
 * JSONObject value from a JSONObject field probably needs to be
 * unmarshalled to a class instance. Double from JSONObject may need to be
 * converted to Float. etc./*from   w  w w.  j  a  v  a  2  s.com*/
 *
 * @param val Value extracted from JSONObject field.
 * @param genericType Type to convert to. Must be generic type. ie. From
 *                    field.getGenericType().
 * @return Object of the given type so it can be assinged to field with
 * field.set().
 * @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException
 */
private static Object valToType(Object val, Type genericType) {
    Object result = null;
    boolean isArray = false;

    Class<?> rawType = null;
    if (genericType instanceof ParameterizedType) {
        rawType = (Class<?>) ((ParameterizedType) genericType).getRawType();
    } else if (genericType instanceof GenericArrayType) {
        rawType = List.class;
        isArray = true;
    } else {
        rawType = (Class<?>) genericType;
    }

    isArray = isArray || rawType.isArray();

    if (val != null && val != JSONObject.NULL) {
        if (rawType.isAssignableFrom(String.class)) {
            if (val instanceof String) {
                result = val;
            } else {
                throw new TypeMismatchException(rawType, val.getClass());
            }
        } else if (isPrimitive(rawType)) {
            result = convertToPrimitiveFieldObj(val, rawType);
        } else if (isArray || rawType.isAssignableFrom(List.class)) {
            if (val instanceof JSONArray) {
                Type itemType = getListItemType(genericType);
                result = JSONToList((JSONArray) val, itemType);

                if (isArray) {
                    List<?> list = (List<?>) result;

                    Class<?> itemClass = null;
                    if (itemType instanceof ParameterizedType) {
                        itemClass = (Class<?>) ((ParameterizedType) itemType).getRawType();
                    } else {
                        itemClass = (Class<?>) itemType;
                    }

                    result = Array.newInstance(itemClass, list.size());
                    int cnt = 0;
                    for (Object i : list) {
                        Array.set(result, cnt, i);
                        cnt += 1;
                    }
                }
            } else {
                throw new TypeMismatchException(JSONArray.class, val.getClass());
            }
        } else if (val instanceof JSONObject) {
            result = JSONToObj((JSONObject) val, rawType);
        }
    }

    return result;
}

From source file:org.apache.axis2.jaxws.utility.ConvertUtils.java

/**
 * Utility function to convert an Object to some desired Class.
 * <p/>/*from   ww  w .j  a  v  a 2 s .c  o  m*/
 * Normally this is used for T[] to List<T> processing. Other conversions are also done (i.e.
 * HashMap <->Hashtable, etc.)
 * <p/>
 * Use the isConvertable() method to determine if conversion is possible. Note that any changes
 * to convert() must also be accompanied by similar changes to isConvertable()
 *
 * @param arg       the array to convert
 * @param destClass the actual class we want
 * @return object of destClass if conversion possible, otherwise returns arg
 */
public static Object convert(Object arg, Class destClass) throws WebServiceException {
    if (destClass == null) {
        return arg;
    }

    if (arg != null && destClass.isAssignableFrom(arg.getClass())) {
        return arg;
    }

    if (log.isDebugEnabled()) {
        String clsName = "null";
        if (arg != null)
            clsName = arg.getClass().getName();
        log.debug("Converting an object of type " + clsName + " to an object of type " + destClass.getName());
    }

    // Convert between Calendar and Date
    if (arg instanceof Calendar && destClass == Date.class) {
        return ((Calendar) arg).getTime();
    }

    // Convert between HashMap and Hashtable
    if (arg instanceof HashMap && destClass == Hashtable.class) {
        return new Hashtable((HashMap) arg);
    }

    if (arg instanceof InputStream && destClass == byte[].class) {

        try {
            InputStream is = (InputStream) arg;
            return getBytesFromStream(is);
        } catch (IOException e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    }

    if (arg instanceof Source && destClass == byte[].class) {
        try {
            if (arg instanceof StreamSource) {
                InputStream is = ((StreamSource) arg).getInputStream();
                if (is != null) {
                    return getBytesFromStream(is);
                }
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Result result = new StreamResult(out);
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.transform((Source) arg, result);
            byte[] bytes = out.toByteArray();
            return bytes;

        } catch (Exception e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    }

    if (arg instanceof DataHandler) {
        try {
            InputStream is = ((DataHandler) arg).getInputStream();
            if (destClass == Image.class) {
                return ImageIO.read(is);
            } else if (destClass == Source.class) {
                return new StreamSource(is);
            }
            byte[] bytes = getBytesFromStream(is);
            return convert(bytes, destClass);
        } catch (Exception e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    }

    if (arg instanceof byte[] && destClass == String.class) {
        return new String((byte[]) arg);
    }

    // If the destination is an array and the source
    // is a suitable component, return an array with 
    // the single item.
    /* REVIEW do we need to support atomic to array conversion ?
    if (arg != null &&
    destClass.isArray() &&
    !destClass.getComponentType().equals(Object.class) &&
    destClass.getComponentType().isAssignableFrom(arg.getClass())) {
    Object array = 
        Array.newInstance(destClass.getComponentType(), 1);
    Array.set(array, 0, arg);
    return array;
    }
    */

    // Return if no conversion is available
    if (!(arg instanceof Collection || (arg != null && arg.getClass().isArray()))) {
        return arg;
    }

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

    // The arg may be an array or List 
    Object destValue = null;
    int length = 0;
    if (arg.getClass().isArray()) {
        length = Array.getLength(arg);
    } else {
        length = ((Collection) arg).size();
    }

    try {
        if (destClass.isArray()) {
            if (destClass.getComponentType().isPrimitive()) {

                Object array = Array.newInstance(destClass.getComponentType(), length);
                // Assign array elements
                if (arg.getClass().isArray()) {
                    for (int i = 0; i < length; i++) {
                        Array.set(array, i, Array.get(arg, i));
                    }
                } else {
                    int idx = 0;
                    for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) {
                        Array.set(array, idx++, i.next());
                    }
                }
                destValue = array;

            } else {
                Object[] array;
                try {
                    array = (Object[]) Array.newInstance(destClass.getComponentType(), length);
                } catch (Exception e) {
                    return arg;
                }

                // Use convert to assign array elements.
                if (arg.getClass().isArray()) {
                    for (int i = 0; i < length; i++) {
                        array[i] = convert(Array.get(arg, i), destClass.getComponentType());
                    }
                } else {
                    int idx = 0;
                    for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) {
                        array[idx++] = convert(i.next(), destClass.getComponentType());
                    }
                }
                destValue = array;
            }
        } else if (Collection.class.isAssignableFrom(destClass)) {
            Collection newList = null;
            try {
                // if we are trying to create an interface, build something
                // that implements the interface
                if (destClass == Collection.class || destClass == List.class) {
                    newList = new ArrayList();
                } else if (destClass == Set.class) {
                    newList = new HashSet();
                } else {
                    newList = (Collection) destClass.newInstance();
                }
            } catch (Exception e) {
                // No FFDC code needed
                // Couldn't build one for some reason... so forget it.
                return arg;
            }

            if (arg.getClass().isArray()) {
                for (int j = 0; j < length; j++) {
                    newList.add(Array.get(arg, j));
                }
            } else {
                for (Iterator j = ((Collection) arg).iterator(); j.hasNext();) {
                    newList.add(j.next());
                }
            }
            destValue = newList;
        } else {
            destValue = arg;
        }
    } catch (Throwable t) {
        throw ExceptionFactory.makeWebServiceException(
                Messages.getMessage("convertUtils", arg.getClass().toString(), destClass.toString()), t);
    }

    return destValue;
}

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

private List<DataValueConvertor> extractConvertors(final Class<?> srcType, final Class<?> targetType) {

    List<DataValueConvertor> foundConvertorList = new LinkedList<DataValueConvertor>();

    // find in list as element to element
    for (DataValueConvertor convertor : DataTypeConvertorList) {
        Pair<Class, Class> typePair = extractConvertorTypeInfo(convertor);
        if (typePair == null) {
            continue;
        }//from w w w.j  a va2 s. c om
        if (typePair.getLeft().isAssignableFrom(srcType)) {
            if (targetType.isAssignableFrom(typePair.getRight())) {// found one
                foundConvertorList.add(convertor);
            } else if (convertor instanceof DataValueConvertorTargetTypeConvertable
                    && typePair.getRight().isAssignableFrom(targetType)) {
                foundConvertorList
                        .add(((DataValueConvertorTargetTypeConvertable) convertor).convert(targetType));
            }
        }
        // @formatter:on
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    // find as array to array
    if (srcType.isArray() && targetType.isArray()) {

        List<DataValueConvertor> componentConvertorList = findConvertor(srcType.getComponentType(),
                targetType.getComponentType());
        List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList,
                new RowConvertor<DataValueConvertor, DataValueConvertor>() {
                    @Override
                    public DataValueConvertor convert(int rowIndex,
                            final DataValueConvertor originalConvertor) {
                        return new DataValueConvertor() {
                            Pair<Class, Class> typePair = extractConvertorTypeInfo(originalConvertor);

                            @Override
                            public Object convert(Object obj) throws UnsupportedValueException {
                                if (typePair == null) {
                                    return null;
                                }

                                int length = Array.getLength(obj);
                                Object targetArray = Array.newInstance(targetType.getComponentType(), length);

                                for (int i = 0; i < length; i++) {
                                    Array.set(targetArray, i, originalConvertor.convert(Array.get(obj, i)));
                                }
                                return targetArray;
                            }
                        };
                    }
                });

        foundConvertorList.addAll(toArrayConvertorList);
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    // find as element to array
    if (targetType.isArray()) {

        List<DataValueConvertor> componentConvertorList = findConvertor(srcType, targetType.getComponentType());
        List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList,
                new RowConvertor<DataValueConvertor, DataValueConvertor>() {
                    @Override
                    public DataValueConvertor convert(int rowIndex,
                            final DataValueConvertor originalConvertor) {
                        return new DataValueConvertor() {
                            private Pair<Class, Class> typePair = extractConvertorTypeInfo(originalConvertor);

                            @Override
                            public Object convert(Object obj) throws UnsupportedValueException {
                                if (typePair == null) {
                                    return null;
                                }
                                Object array = Array.newInstance(targetType.getComponentType(), 1);
                                Array.set(array, 0, originalConvertor.convert(obj));
                                return array;
                            }
                        };
                    }
                });

        foundConvertorList.addAll(toArrayConvertorList);
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    // find as array to element
    if (srcType.isArray()) {
        List<DataValueConvertor> componentConvertorList = findConvertor(srcType.getComponentType(), targetType);
        List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList,
                new RowConvertor<DataValueConvertor, DataValueConvertor>() {
                    @Override
                    public DataValueConvertor convert(int rowIndex,
                            final DataValueConvertor originalConvertor) {
                        return new DataValueConvertor() {
                            @Override
                            public Object convert(Object obj) throws UnsupportedValueException {
                                int length = Array.getLength(obj);
                                if (length == 0) {
                                    return null;
                                } else {
                                    return originalConvertor.convert(Array.get(obj, 0));
                                }
                            }
                        };
                    }
                });

        foundConvertorList.addAll(toArrayConvertorList);
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    return foundConvertorList;
}

From source file:org.kie.remote.jaxb.gen.util.JaxbUnknownAdapter.java

public Object recursiveUnmarhsal(Object o) throws Exception {
    if (o instanceof org.kie.remote.jaxb.gen.List) {
        org.kie.remote.jaxb.gen.List wrapper = (org.kie.remote.jaxb.gen.List) o;
        List<Object> elements = wrapper.getElements();
        int size = 0;
        if (elements != null) {
            size = elements.size();/*from  w  ww  .j  a v  a  2  s  .  c o  m*/
        }
        if (wrapper.getType() == null) {
            List<Object> list = new ArrayList<Object>(size);
            return convertSerializedElementsToCollection(elements, list);
        } else {
            switch (wrapper.getType()) {
            case LIST:
                List<Object> list = new ArrayList<Object>(size);
                return convertSerializedElementsToCollection(elements, list);
            case SET:
                Set<Object> set = new HashSet<Object>(size);
                return convertSerializedElementsToCollection(elements, set);
            case MAP:
                Map<String, Object> map = new HashMap<String, Object>(size);
                if (size > 0) {
                    for (Object keyValueObj : elements) {
                        JaxbStringObjectPair keyValue = (JaxbStringObjectPair) keyValueObj;
                        Object key = keyValue.getKey();
                        Object value = convertSerializedObjectToObject(keyValue.getValue());
                        map.put(key.toString(), value);
                    }
                }
                return map;
            case ARRAY:
                List<Object> objList = wrapper.getElements();
                int length = objList.size();
                String componentTypeName = wrapper.getComponentType();
                Class realArrComponentType = null;
                realArrComponentType = getClass(componentTypeName);

                // create and fill array
                Object realArr = Array.newInstance(realArrComponentType, objList.size());
                for (int i = 0; i < length; ++i) {
                    Array.set(realArr, i, objList.get(i));
                }
                return realArr;
            default:
                throw new IllegalArgumentException(
                        "Unknown JAXB collection wrapper type: " + wrapper.getType().toString());
            }
        }
    } else if (o instanceof JaxbStringObjectPair[]) {
        // backwards compatibile: remove in 7.0.x
        JaxbStringObjectPair[] value = (JaxbStringObjectPair[]) o;
        Map<Object, Object> r = new HashMap<Object, Object>();
        for (JaxbStringObjectPair p : value) {
            if (p.getValue() instanceof org.kie.remote.jaxb.gen.List) {
                r.put(p.getKey(), new ArrayList(
                        Arrays.asList(((org.kie.remote.jaxb.gen.List) p.getValue()).getElements())));
            } else {
                r.put(p.getKey(), p.getValue());
            }
        }
        return r;
    } else {
        return o;
    }
}

From source file:jp.terasoluna.fw.web.struts.form.DynaValidatorActionFormEx.java

/**
 * CfbNXtv?peBZbg?B//w ww.  ja  va 2  s .  c  o  m
 *
 * <p>
 *  StrutsDynaActionFormv?peB^
 *  Listz^gpO??A
 *  TCY?AITCY
 *  ?X?A???g?B
 * </p>
 *
 * @param name Zbg?tB?[h
 * @param index Zbg?CfbNX
 * @param value Zbg?tB?[hl
 */
@SuppressWarnings("unchecked")
@Override
public void set(String name, int index, Object value) {

    if (log.isDebugEnabled()) {
        log.debug("set(" + name + ", " + index + ", " + value + ") called.");
    }

    Object prop = dynaValues.get(name);
    if (prop == null) {
        throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'");
    } else if (prop.getClass().isArray()) {
        if (index < Array.getLength(prop)) {
            Array.set(prop, index, value);
        } else {
            // CfbNX`FbN
            ActionFormUtil.checkIndexLength(index);
            // ?VKz??
            Object newArray = Array.newInstance(prop.getClass().getComponentType(), index + 1);
            // zR|?[lgRs?[
            System.arraycopy(prop, 0, newArray, 0, Array.getLength(prop));
            // R|?[lgZbg
            Array.set(newArray, index, value);
            // Q?Rs?[
            prop = newArray;
        }
        dynaValues.put(name, prop);
    } else if (prop instanceof List) {
        if (index < ((List) prop).size()) {
            ((List) prop).set(index, value);
        } else {
            // CfbNX`FbN
            ActionFormUtil.checkIndexLength(index);
            Object[] oldValues = ((List) prop).toArray();
            Object[] newValues = (Object[]) Array.newInstance(oldValues.getClass().getComponentType(),
                    index + 1);
            System.arraycopy(oldValues, 0, newValues, 0, oldValues.length);
            newValues[index] = value;
            ((List) prop).clear();
            ((List) prop).addAll(Arrays.asList(newValues));
        }
        dynaValues.put(name, prop);
    } else {
        throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'");
    }

}

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

/**
 * Modifies the index'th element of the supplied collection.
 * Converts the value to the required type if necessary.
 * @param collection to edit//  w  ww . j  a va 2s . co  m
 * @param index to replace
 * @param value new value
 */
public static void setValue(Object collection, int index, Object value) {
    collection = getValue(collection);
    if (collection != null) {
        if (collection.getClass().isArray()) {
            Array.set(collection, index, convert(value, collection.getClass().getComponentType()));
        } else if (collection instanceof List) {
            ((List) collection).set(index, value);
        } else if (collection instanceof Collection) {
            throw new UnsupportedOperationException(
                    "Cannot set value of an element of a " + collection.getClass().getName());
        }
    }
}