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:org.openqa.jetty.xml.XmlConfiguration.java

private Object newArray(Object obj, XmlParser.Node node) throws NoSuchMethodException, ClassNotFoundException,
        InvocationTargetException, IllegalAccessException {
    // Get the type
    Class aClass = java.lang.Object.class;
    String type = node.getAttribute("type");
    String id = node.getAttribute("id");
    if (type != null) {
        aClass = TypeUtil.fromName(type);
        if (aClass == null) {
            if ("String".equals(type))
                aClass = java.lang.String.class;
            else if ("URL".equals(type))
                aClass = java.net.URL.class;
            else if ("InetAddress".equals(type))
                aClass = java.net.InetAddress.class;
            else if ("InetAddrPort".equals(type))
                aClass = org.openqa.jetty.util.InetAddrPort.class;
            else//w  w w  . j  a  v  a 2s.  com
                aClass = Loader.loadClass(XmlConfiguration.class, type);
        }
    }

    Object array = Array.newInstance(aClass, node.size());
    if (id != null)
        _idMap.put(id, obj);

    for (int i = 0; i < node.size(); i++) {
        Object o = node.get(i);
        if (o instanceof String)
            continue;
        XmlParser.Node item = (XmlParser.Node) o;
        if (!item.getTag().equals("Item"))
            throw new IllegalStateException("Not an Item");
        id = item.getAttribute("id");
        Object v = value(obj, item);
        if (v != null)
            Array.set(array, i, v);
        if (id != null)
            _idMap.put(id, v);
    }

    return array;
}

From source file:org.xmlsh.util.JavaUtils.java

@SuppressWarnings("rawtypes")
public static void setNamePositionalValue(Object obj, int index, Object object)
        throws InvalidArgumentException {
    if (obj.getClass().isArray()) {
        Array.set(obj, index, object);
    } else if (obj instanceof List) {
        ((List) obj).set(index, object);
    } else//from  ww w.j a  va  2  s  .c  om
        throw new InvalidArgumentException("No positional index for class: " + getClassName(obj));
}

From source file:org.springframework.beans.BeanWrapperImpl.java

private Object newValue(Class<?> type, TypeDescriptor desc, String name) {
    try {/*from w  w w  . j a  v  a  2 s  .co  m*/
        if (type.isArray()) {
            Class<?> componentType = type.getComponentType();
            // TODO - only handles 2-dimensional arrays
            if (componentType.isArray()) {
                Object array = Array.newInstance(componentType, 1);
                Array.set(array, 0, Array.newInstance(componentType.getComponentType(), 0));
                return array;
            } else {
                return Array.newInstance(componentType, 0);
            }
        } else if (Collection.class.isAssignableFrom(type)) {
            TypeDescriptor elementDesc = (desc != null ? desc.getElementTypeDescriptor() : null);
            return CollectionFactory.createCollection(type,
                    (elementDesc != null ? elementDesc.getType() : null), 16);
        } else if (Map.class.isAssignableFrom(type)) {
            TypeDescriptor keyDesc = (desc != null ? desc.getMapKeyTypeDescriptor() : null);
            return CollectionFactory.createMap(type, (keyDesc != null ? keyDesc.getType() : null), 16);
        } else {
            return type.newInstance();
        }
    } catch (Exception ex) {
        // TODO: Root cause exception context is lost here; just exception message preserved.
        // Should we throw another exception type that preserves context instead?
        throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + name,
                "Could not instantiate property type [" + type.getName()
                        + "] to auto-grow nested property path: " + ex);
    }
}

From source file:Main.java

/**
 * Underlying implementation of add(array, index, element) methods.
 * The last parameter is the class, which may not equal element.getClass
 * for primitives.// ww  w  .j a v  a2s .  co  m
 *
 * @param array  the array to add the element to, may be {@code null}
 * @param index  the position of the new object
 * @param element  the object to add
 * @param clss the type of the element being added
 * @return A new array containing the existing elements and the new element
 */
private static Object add(final Object array, final int index, final Object element, final Class<?> clss) {
    if (array == null) {
        if (index != 0) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
        }
        final Object joinedArray = Array.newInstance(clss, 1);
        Array.set(joinedArray, 0, element);
        return joinedArray;
    }
    final int length = Array.getLength(array);
    if (index > length || index < 0) {
        throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
    }
    final Object result = Array.newInstance(clss, 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 result;
}

From source file:com.sun.faces.config.ManagedBeanFactory.java

/**
 * <li><p> Call the property getter, if it exists.</p></li>
 * <p/>/* w w w. j a  va 2s. c  o m*/
 * <li><p>If the getter returns null or doesn't exist, create a
 * java.util.ArrayList(), otherwise use the returned Object (an array or
 * a java.util.List).</p></li>
 * <p/>
 * <li><p>If a List was returned or created in step 2), add all
 * elements defined by nested &lt;value&gt; elements in the order
 * they are listed, converting values defined by nested
 * &lt;value&gt; elements to the type defined by
 * &lt;value-class&gt;. If a &lt;value-class&gt; is not defined, use
 * the value as-is (i.e., as a java.lang.String). Add null for each
 * &lt;null-value&gt; element.</p></li>
 * <p/>
 * <li><p> If an array was returned in step 2), create a
 * java.util.ArrayList and copy all elements from the returned array to
 * the new List, auto-boxing elements of a primitive type. Add all
 * elements defined by nested &lt;value&gt; elements as described in step
 * 3).</p></li>
 * <p/>
 * <li><p> If a new java.util.List was created in step 2) and the
 * property is of type List, set the property by calling the setter
 * method, or log an error if there is no setter method.</p></li>
 * <p/>
 * <li><p> If a new java.util.List was created in step 4), convert
 * the * List to array of the same type as the property and set the
 * property by * calling the setter method, or log an error if there
 * is no setter * method.</p></li>
 */

private void setArrayOrListPropertiesIntoBean(Object bean, ManagedPropertyBean property) throws Exception {
    Object result = null;
    boolean getterIsNull = true, getterIsArray = false;
    List valuesForBean = null;
    Class valueType = java.lang.String.class, propertyType = null;

    String propertyName = property.getPropertyName();

    try {
        // see if there is a getter
        result = PropertyUtils.getProperty(bean, propertyName);
        getterIsNull = (null == result) ? true : false;

        propertyType = PropertyUtils.getPropertyType(bean, propertyName);
        getterIsArray = propertyType.isArray();

    } catch (NoSuchMethodException nsme) {
        // it's valid to not have a getter.
    }

    // the property has to be either a List or Array
    if (!getterIsArray) {
        if (null != propertyType && !java.util.List.class.isAssignableFrom(propertyType)) {
            throw new FacesException(
                    Util.getExceptionMessageString(Util.MANAGED_BEAN_CANNOT_SET_LIST_ARRAY_PROPERTY_ID,
                            new Object[] { propertyName, managedBean.getManagedBeanName() }));
        }
    }

    //
    // Deal with the possibility of the getter returning existing
    // values.
    //

    // if the getter returned non-null
    if (!getterIsNull) {
        // if what it returned was an array
        if (getterIsArray) {
            valuesForBean = new ArrayList();
            for (int i = 0, len = Array.getLength(result); i < len; i++) {
                // add the existing values
                valuesForBean.add(Array.get(result, i));
            }
        } else {
            // if what it returned was not a List
            if (!(result instanceof List)) {
                // throw an exception                    
                throw new FacesException(
                        Util.getExceptionMessageString(Util.MANAGED_BEAN_EXISTING_VALUE_NOT_LIST_ID,
                                new Object[] { propertyName, managedBean.getManagedBeanName() }));
            }
            valuesForBean = (List) result;
        }
    } else {

        // getter returned null
        result = valuesForBean = new ArrayList();
    }

    // at this point valuesForBean contains the existing values from
    // the bean, or no values if the bean had no values.  In any
    // case, we can proceed to add values from the config file.
    valueType = copyListEntriesFromConfigToList(property.getListEntries(), valuesForBean);

    // at this point valuesForBean has the values to be set into the
    // bean.

    if (getterIsArray) {
        // convert back to Array
        result = Array.newInstance(valueType, valuesForBean.size());
        for (int i = 0, len = valuesForBean.size(); i < len; i++) {
            if (valueType == Boolean.TYPE) {
                Array.setBoolean(result, i, ((Boolean) valuesForBean.get(i)).booleanValue());
            } else if (valueType == Byte.TYPE) {
                Array.setByte(result, i, ((Byte) valuesForBean.get(i)).byteValue());
            } else if (valueType == Double.TYPE) {
                Array.setDouble(result, i, ((Double) valuesForBean.get(i)).doubleValue());
            } else if (valueType == Float.TYPE) {
                Array.setFloat(result, i, ((Float) valuesForBean.get(i)).floatValue());
            } else if (valueType == Integer.TYPE) {
                Array.setInt(result, i, ((Integer) valuesForBean.get(i)).intValue());
            } else if (valueType == Character.TYPE) {
                Array.setChar(result, i, ((Character) valuesForBean.get(i)).charValue());
            } else if (valueType == Short.TYPE) {
                Array.setShort(result, i, ((Short) valuesForBean.get(i)).shortValue());
            } else if (valueType == Long.TYPE) {
                Array.setLong(result, i, ((Long) valuesForBean.get(i)).longValue());
            } else {
                Array.set(result, i, valuesForBean.get(i));
            }
        }
    } else {
        result = valuesForBean;
    }

    if (getterIsNull || getterIsArray) {
        PropertyUtils.setProperty(bean, propertyName, result);
    }

}

From source file:org.janusgraph.graphdb.serializer.SerializerTest.java

License:asdf

private static Factory getArrayFactory(final Class ct, final Factory f) {
    return () -> {
        final int length = random.nextInt(100);
        final Object array = Array.newInstance(ct, length);
        for (int i = 0; i < length; i++) {
            if (ct == boolean.class)
                Array.setBoolean(array, i, (Boolean) f.newInstance());
            else if (ct == byte.class)
                Array.setByte(array, i, (Byte) f.newInstance());
            else if (ct == short.class)
                Array.setShort(array, i, (Short) f.newInstance());
            else if (ct == int.class)
                Array.setInt(array, i, (Integer) f.newInstance());
            else if (ct == long.class)
                Array.setLong(array, i, (Long) f.newInstance());
            else if (ct == float.class)
                Array.setFloat(array, i, (Float) f.newInstance());
            else if (ct == double.class)
                Array.setDouble(array, i, (Double) f.newInstance());
            else if (ct == char.class)
                Array.setChar(array, i, (Character) f.newInstance());
            else/*from  w  ww .j  a  va2 s  .  c  o  m*/
                Array.set(array, i, f.newInstance());
        }
        return array;
    };
}

From source file:org.apache.hadoop.yarn.api.TestPBImplRecords.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static Object genTypeValue(Type type) {
    Object ret = typeValueCache.get(type);
    if (ret != null) {
        return ret;
    }/*from  ww w.j a v a  2s.  c o  m*/
    // only use positive primitive values
    if (type.equals(boolean.class)) {
        return rand.nextBoolean();
    } else if (type.equals(byte.class)) {
        return bytes[rand.nextInt(4)];
    } else if (type.equals(int.class)) {
        return rand.nextInt(1000000);
    } else if (type.equals(long.class)) {
        return Long.valueOf(rand.nextInt(1000000));
    } else if (type.equals(float.class)) {
        return rand.nextFloat();
    } else if (type.equals(double.class)) {
        return rand.nextDouble();
    } else if (type.equals(String.class)) {
        return String.format("%c%c%c", 'a' + rand.nextInt(26), 'a' + rand.nextInt(26), 'a' + rand.nextInt(26));
    } else if (type instanceof Class) {
        Class clazz = (Class) type;
        if (clazz.isArray()) {
            Class compClass = clazz.getComponentType();
            if (compClass != null) {
                ret = Array.newInstance(compClass, 2);
                Array.set(ret, 0, genTypeValue(compClass));
                Array.set(ret, 1, genTypeValue(compClass));
            }
        } else if (clazz.isEnum()) {
            Object[] values = clazz.getEnumConstants();
            ret = values[rand.nextInt(values.length)];
        } else if (clazz.equals(ByteBuffer.class)) {
            // return new ByteBuffer every time
            // to prevent potential side effects
            ByteBuffer buff = ByteBuffer.allocate(4);
            rand.nextBytes(buff.array());
            return buff;
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        Type rawType = pt.getRawType();
        Type[] params = pt.getActualTypeArguments();
        // only support EnumSet<T>, List<T>, Set<T>, Map<K,V>
        if (rawType.equals(EnumSet.class)) {
            if (params[0] instanceof Class) {
                Class c = (Class) (params[0]);
                return EnumSet.allOf(c);
            }
        }
        if (rawType.equals(List.class)) {
            ret = Lists.newArrayList(genTypeValue(params[0]));
        } else if (rawType.equals(Set.class)) {
            ret = Sets.newHashSet(genTypeValue(params[0]));
        } else if (rawType.equals(Map.class)) {
            Map<Object, Object> map = Maps.newHashMap();
            map.put(genTypeValue(params[0]), genTypeValue(params[1]));
            ret = map;
        }
    }
    if (ret == null) {
        throw new IllegalArgumentException("type " + type + " is not supported");
    }
    typeValueCache.put(type, ret);
    return ret;
}

From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java

private Object newValue(Class<?> type, TypeDescriptor desc, String name) {
    try {// ww  w.j a v a  2  s . c o m
        if (type.isArray()) {
            Class<?> componentType = type.getComponentType();
            // #TO#DO# - only handles 2-dimensional arrays
            if (componentType.isArray()) {
                Object array = Array.newInstance(componentType, 1);
                Array.set(array, 0, Array.newInstance(componentType.getComponentType(), 0));
                return array;
            } else {
                return Array.newInstance(componentType, 0);
            }
        } else if (Collection.class.isAssignableFrom(type)) {
            TypeDescriptor elementDesc = (desc != null ? desc.getElementTypeDescriptor() : null);
            return CollectionFactory.createCollection(type,
                    (elementDesc != null ? elementDesc.getType() : null), 16);
        } else if (Map.class.isAssignableFrom(type)) {
            TypeDescriptor keyDesc = (desc != null ? desc.getMapKeyTypeDescriptor() : null);
            return CollectionFactory.createMap(type, (keyDesc != null ? keyDesc.getType() : null), 16);
        } else {
            return type.newInstance();
        }
    } catch (Exception ex) {
        // #TO#DO#: Root cause exception context is lost here; just exception message preserved.
        // Should we throw another exception type that preserves context instead?
        throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + name,
                "Could not instantiate property type [" + type.getName()
                        + "] to auto-grow nested property path: " + ex);
    }
}

From source file:weave.servlets.WeaveServlet.java

/**
 * Tries to convert value to the given type.
 * @param value The value to cast to a new type.
 * @param type The desired type./*from   w ww  .j a  v a 2s  . c om*/
 * @return The value, which may have been cast as the new type.
 */
protected Object cast(Object value, Class<?> type) throws RemoteException {
    if (type.isInstance(value))
        return value;

    try {
        if (value == null) // null -> NaN
        {
            if (type == double.class || type == Double.class)
                value = Double.NaN;
            else if (type == float.class || type == Float.class)
                value = Float.NaN;
            return value;
        }

        if (value instanceof Map) // Map -> Java Bean
        {
            Object bean = type.newInstance();
            for (Field field : type.getFields()) {
                Object fieldValue = ((Map<?, ?>) value).get(field.getName());
                fieldValue = cast(fieldValue, field.getType());
                field.set(bean, fieldValue);
            }
            return bean;
        }

        if (type.isArray()) // ? -> T[]
        {
            if (value instanceof String) // String -> String[]
                value = CSVParser.defaultParser.parseCSVRow((String) value, true);

            if (value instanceof List) // List -> Object[]
                value = ((List<?>) value).toArray();

            if (value.getClass().isArray()) // T1[] -> T2[]
            {
                int n = Array.getLength(value);
                Class<?> itemType = type.getComponentType();
                Object output = Array.newInstance(itemType, n);
                while (n-- > 0)
                    Array.set(output, n, cast(Array.get(value, n), itemType));
                return output;
            }
        }

        if (Collection.class.isAssignableFrom(type)) // ? -> <? extends Collection>
        {
            value = cast(value, Object[].class); // ? -> Object[]

            if (value.getClass().isArray()) // T1[] -> Vector<T2>
            {
                int n = Array.getLength(value);
                List<Object> output = new Vector<Object>(n);
                TypeVariable<?>[] itemTypes = type.getTypeParameters();
                Class<?> itemType = itemTypes.length > 0 ? itemTypes[0].getClass() : null;
                while (n-- > 0) {
                    Object item = Array.get(value, n);
                    if (itemType != null)
                        item = cast(item, itemType); // T1 -> T2
                    output.set(n, item);
                }
                return output;
            }
        }

        if (value instanceof String) // String -> ?
        {
            String string = (String) value;

            // String -> primitive
            if (type == char.class || type == Character.class)
                return string.charAt(0);
            if (type == byte.class || type == Byte.class)
                return Byte.parseByte(string);
            if (type == long.class || type == Long.class)
                return Long.parseLong(string);
            if (type == int.class || type == Integer.class)
                return Integer.parseInt(string);
            if (type == short.class || type == Short.class)
                return Short.parseShort(string);
            if (type == float.class || type == Float.class)
                return Float.parseFloat(string);
            if (type == double.class || type == Double.class)
                return Double.parseDouble(string);
            if (type == boolean.class || type == Boolean.class)
                return string.equalsIgnoreCase("true");

            if (type == InputStream.class) // String -> InputStream
            {
                try {
                    return new ByteArrayInputStream(string.getBytes("UTF-8"));
                } catch (Exception e) {
                    return null;
                }
            }
        }

        if (value instanceof Number) // Number -> primitive
        {
            Number number = (Number) value;
            if (type == byte.class || type == Byte.class)
                return number.byteValue();
            if (type == long.class || type == Long.class)
                return number.longValue();
            if (type == int.class || type == Integer.class)
                return number.intValue();
            if (type == short.class || type == Short.class)
                return number.shortValue();
            if (type == float.class || type == Float.class)
                return number.floatValue();
            if (type == double.class || type == Double.class)
                return number.doubleValue();
            if (type == char.class || type == Character.class)
                return Character.toChars(number.intValue())[0];
            if (type == boolean.class || type == Boolean.class)
                return !Double.isNaN(number.doubleValue()) && number.intValue() != 0;
        }
    } catch (Exception e) {
        throw new RemoteException(String.format("Unable to cast %s to %s", value.getClass().getSimpleName(),
                type.getSimpleName()), e);
    }

    // Return original value if not handled above.
    // Primitives and their Object equivalents will cast automatically.
    return value;
}

From source file:org.seasar.struts.action.S2RequestProcessor.java

/**
 * ????/*from  w ww  . ja va2s .c o  m*/
 * 
 * @param array
 *            ?
 * @param indexes
 *            ??
 * @param elementType
 *            ????
 * @return ??
 */
protected Object expand(Object array, int[] indexes, Class<?> elementType) {
    int length = Array.getLength(array);
    if (length <= indexes[0]) {
        int[] newIndexes = new int[indexes.length];
        newIndexes[0] = indexes[0] + 1;
        Object newArray = Array.newInstance(elementType, newIndexes);
        System.arraycopy(array, 0, newArray, 0, length);
        array = newArray;
    }
    if (indexes.length > 1) {
        int[] newIndexes = new int[indexes.length - 1];
        for (int i = 1; i < indexes.length; i++) {
            newIndexes[i - 1] = indexes[i];
        }
        Array.set(array, indexes[0], expand(Array.get(array, indexes[0]), newIndexes, elementType));
    }
    return array;
}