Example usage for java.lang.reflect Array get

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

Introduction

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

Prototype

public static native Object get(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

Source Link

Document

Returns the value of the indexed component in the specified array object.

Usage

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) {/*from www. j  a v a2 s .c  o  m*/
    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:org.jdto.impl.CoreBeanModifier.java

private Object copyToProperArray(Class expectedType, Object finalValue) {
    Object ret = Array.newInstance(expectedType.getComponentType(), Array.getLength(finalValue));

    for (int i = 0; i < Array.getLength(finalValue); i++) {
        Array.set(ret, i, Array.get(finalValue, i));
    }/*from w ww .  j a v a  2 s .c  om*/

    return ret;
}

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

/**
 * Utility function to convert an Object to some desired Class.
 * <p/>/* w ww .j a  v a  2  s .  com*/
 * 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:ArrayUtils.java

/**
 * Merges all elements of a set of arrays into a single array with no
 * duplicates. For primitive types.//from w  ww  .  j a v a 2s  . c om
 * 
 * @param type
 *            The type of the result
 * @param arrays
 *            The arrays to merge
 * @return A new array containing all elements of <code>array1</code> and
 *         all elements of <code>array2</code> that are not present in
 *         <code>array1</code>
 * @throws NullPointerException
 *             If either array is null
 * @throws ArrayStoreException
 *             If elements in the arrays are incompatible with
 *             <code>type</code>
 */
public static Object mergeInclusiveP(Class<?> type, Object... arrays) {
    java.util.LinkedHashSet<Object> set = new java.util.LinkedHashSet<Object>();
    int i, j;
    for (i = 0; i < arrays.length; i++) {
        int len = Array.getLength(arrays[i]);
        for (j = 0; j < len; j++)
            set.add(Array.get(arrays[i], j));
    }
    Object ret = Array.newInstance(type, set.size());
    i = 0;
    for (Object el : set) {
        put(ret, el, i);
        i++;
    }
    return ret;
}

From source file:gool.generator.common.CommonCodeGenerator.java

/**
 * Produces code for a constant./*  www  .  ja v  a 2  s .c  o m*/
 * 
 * @param constant
 *            a constant value.
 * @return the formatted constant value.
 */
@Override
public String getCode(Constant constant) {
    if (constant.getType() instanceof TypeArray) {
        StringBuffer sb = new StringBuffer();

        int size = Array.getLength(constant.getValue());
        boolean escape = ((TypeArray) constant.getType()).getElementType() instanceof TypeString;

        sb.append("{");
        for (int i = 0; i < size; i++) {
            if (escape) {
                return "\"" + StringEscapeUtils.escapeJava(Array.get(constant.getValue(), i).toString()) + "\"";
            } else {
                sb.append(Array.get(constant.getValue(), i));
            }
            sb.append(",");
        }
        sb.append("}");
        return sb.toString();
    } else if (constant.getType() == TypeString.INSTANCE) {
        return "\"" + StringEscapeUtils.escapeJava(constant.getValue().toString()) + "\"";
    } else if (constant.getType() == TypeChar.INSTANCE) {
        return "'" + StringEscapeUtils.escapeJava(constant.getValue().toString()) + "'";
    }
    return constant.getValue().toString();
}

From source file:org.apache.velocity.tools.generic.DisplayTool.java

/**
 * Formats a specified property of collection or array of objects into the
 * form "A&lt;delim&gt;B&lt;finaldelim&gt;C".
 * /* w ww .ja v a2 s .c  om*/
 * @param list A collection or array.
 * @param delim A String.
 * @param finaldelim A String.
 * @param property An object property to format.
 * @return A String.
 */
public String list(Object list, String delim, String finaldelim, String property) {
    if (list == null) {
        return null;
    }
    if (list instanceof Collection) {
        return format((Collection) list, delim, finaldelim, property);
    }
    Collection items;
    if (list.getClass().isArray()) {
        int size = Array.getLength(list);
        items = new ArrayList(size);
        for (int i = 0; i < size; i++) {
            items.add(Array.get(list, i));
        }
    } else {
        items = Collections.singletonList(list);
    }
    return format(items, delim, finaldelim, property);
}

From source file:com.facebook.LegacyTokenCacheTest.java

private static void assertArrayEquals(Object a1, Object a2) {
    assertNotNull(a1);//  w  ww  .  j  a va2  s  .co m
    assertNotNull(a2);
    assertEquals(a1.getClass(), a2.getClass());
    assertTrue("Not an array", a1.getClass().isArray());

    int length = Array.getLength(a1);
    assertEquals(length, Array.getLength(a2));
    for (int i = 0; i < length; i++) {
        Object a1Value = Array.get(a1, i);
        Object a2Value = Array.get(a2, i);

        assertEquals(a1Value, a2Value);
    }
}

From source file:adams.ml.Dataset.java

public void setMappingFromDataRow(DataRow dr) {
    for (String key : dr.getKeys()) {
        BaseData bd = dr.get(key);//from  w w  w  .  jav a2  s.co m
        if (bd != null) {
            if (bd.isNumeric()) {
                setType(key, BaseData.Type.NUMERIC);
            } else if (bd.isArray()) {
                if (Array.getLength(bd.getData()) > 0) {
                    Object ao = Array.get(bd.getData(), 0);
                    if (BaseData.isNumeric(ao)) {
                        setType(key, BaseData.Type.NUMERIC, Array.getLength(bd.getData()));
                    } else {
                        setType(key, BaseData.Type.STRING, Array.getLength(bd.getData()));
                    }
                }
            } else {
                setType(key, BaseData.Type.STRING);
            }
        }
    }
}

From source file:com.microsoft.tfs.core.internal.db.DBStatement.java

private void setParameters(final PreparedStatement ps, final Object args) throws SQLException {
    if (args == null) {
        return;/* w w w. ja v  a 2  s.com*/
    }

    if (!args.getClass().isArray()) {
        ps.setObject(1, args);
    } else {
        final int len = Array.getLength(args);
        for (int i = 0; i < len; i++) {
            ps.setObject(i + 1, Array.get(args, i));
        }
    }
}

From source file:org.paxml.tag.sql.DdlTag.java

private String[] getArray(Object value) {
    if (value == null) {
        return new String[0];
    }/*  w ww .  jav  a  2  s .c  o m*/

    Iterator it = null;

    if (value instanceof Iterable) {
        it = ((Iterable) value).iterator();
    } else if (value instanceof Iterator) {
        it = (Iterator) value;
    } else if (value.getClass().isArray()) {
        int len = Array.getLength(value);
        List<String> list = new ArrayList<String>(len);
        for (int i = 0; i < len; i++) {
            Object item = Array.get(value, i);
            if (item != null) {
                list.add(item.toString());
            }
        }
        return list.toArray(new String[list.size()]);
    }

    if (it != null) {
        List<String> list = new ArrayList<String>();
        while (it.hasNext()) {
            Object next = it.next();
            if (next != null) {
                list.add(next.toString());
            }
        }
        return list.toArray(new String[list.size()]);
    }

    return new String[] { value.toString() };

}