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

/**
 * Removes all contents of <code>array2</code> from <code>array1</code>. All
 * instances of <code>array2</code> will also be removed from
 * <code>array1</code>. For primitive types.
 * //from   w w  w  .j a va2 s  .c o  m
 * @param array1
 *            The array to remove elements from
 * @param array2
 *            The array containing the elements to remove; or the element to
 *            remove itself
 * @return <code>array1</code> missing all the contents of
 *         <code>array2</code>
 */
public static Object removeAllP(Object array1, Object array2) {
    if (array1 == null || array2 == null)
        return array1;
    if (!array1.getClass().isArray())
        return null;
    if (!array2.getClass().isArray())
        array2 = new Object[] { array2 };
    else
        array2 = addP(array2, array2);
    java.util.BitSet remove = new java.util.BitSet();
    int len1 = Array.getLength(array1);
    int len2 = Array.getLength(array2);
    int i, j;
    for (i = 0; i < len1; i++) {
        for (j = 0; j < len2; j++) {
            if (equals(Array.get(array1, i), Array.get(array2, j))) {
                remove.set(i);
                break;
            }
        }
    }
    Object ret = Array.newInstance(array1.getClass().getComponentType(), len1 - remove.cardinality());
    // This copying section might be replaced by a more efficient version
    // using System.arraycopy()--this would be much faster than reflection,
    // especially for large arrays needing only a few elements removed
    for (i = 0, j = 0; i < len1; i++) {
        if (!remove.get(i)) {
            put(ret, Array.get(array1, i), j);
            j++;
        }
    }
    return ret;
}

From source file:eu.qualityontime.commons.QPropertyUtilsBean.java

public Object _getIndexedProperty(final Object bean, final String name, final int index) throws Exception {

    if (bean == null) {
        throw new IllegalArgumentException("No bean specified");
    }/*w w w .  ja  va 2 s. c  o m*/
    if (name == null || name.length() == 0) {
        if (bean.getClass().isArray()) {
            return Array.get(bean, index);
        } else if (bean instanceof List) {
            return ((List<?>) bean).get(index);
        }
    }
    if (name == null) {
        throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'");
    }

    if (name.startsWith("@")) {
        Object f = FieldUtils.readField(bean, trimAnnotations(name));
        if (null == f) {
            if (name.endsWith("?"))
                return null;
            else
                throw new NestedNullException();
        }
        if (f.getClass().isArray())
            return Array.get(f, index);
        else if (f instanceof List)
            return ((List<?>) f).get(index);
    }
    // Retrieve the property descriptor for the specified property
    final PropertyDescriptor descriptor = getPropertyDescriptor(bean, trimAnnotations(name));
    if (descriptor == null) {
        throw new NoSuchMethodException(
                "Unknown property '" + name + "' on bean class '" + bean.getClass() + "'");
    }

    // Call the indexed getter method if there is one
    if (descriptor instanceof IndexedPropertyDescriptor) {
        Method readMethod = ((IndexedPropertyDescriptor) descriptor).getIndexedReadMethod();
        readMethod = MethodUtils.getAccessibleMethod(bean.getClass(), readMethod);
        if (readMethod != null) {
            final Object[] subscript = new Object[1];
            subscript[0] = new Integer(index);
            try {
                return invokeMethod(readMethod, bean, subscript);
            } catch (final InvocationTargetException e) {
                if (e.getTargetException() instanceof IndexOutOfBoundsException) {
                    throw (IndexOutOfBoundsException) e.getTargetException();
                } else {
                    throw e;
                }
            }
        }
    }

    // Otherwise, the underlying property must be an array
    final Method readMethod = getReadMethod(bean.getClass(), descriptor);
    if (readMethod == null) {
        throw new NoSuchMethodException(
                "Property '" + name + "' has no " + "getter method on bean class '" + bean.getClass() + "'");
    }

    // Call the property getter and return the value
    final Object value = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY);
    if (null == value && name.endsWith("?"))
        return null;
    if (!value.getClass().isArray()) {
        if (!(value instanceof java.util.List)) {
            throw new IllegalArgumentException(
                    "Property '" + name + "' is not indexed on bean class '" + bean.getClass() + "'");
        } else {
            // get the List's value
            return ((java.util.List<?>) value).get(index);
        }
    } else {
        // get the array's value
        try {
            return Array.get(value, index);
        } catch (final ArrayIndexOutOfBoundsException e) {
            throw new ArrayIndexOutOfBoundsException(
                    "Index: " + index + ", Size: " + Array.getLength(value) + " for property '" + name + "'");
        }
    }

}

From source file:org.enerj.apache.commons.beanutils.BeanUtilsBean.java

/**
 * Return the value of the specified array property of the specified
 * bean, as a String array./*from www  .j  a  va  2  s  .c o m*/
 *
 * @param bean Bean whose property is to be extracted
 * @param name Name of the property to be extracted
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 * @exception NoSuchMethodException if an accessor method for this
 *  property cannot be found
 */
public String[] getArrayProperty(Object bean, String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    Object value = getPropertyUtils().getProperty(bean, name);
    if (value == null) {
        return (null);
    } else if (value instanceof Collection) {
        ArrayList values = new ArrayList();
        Iterator items = ((Collection) value).iterator();
        while (items.hasNext()) {
            Object item = items.next();
            if (item == null) {
                values.add((String) null);
            } else {
                // convert to string using convert utils
                values.add(getConvertUtils().convert(item));
            }
        }
        return ((String[]) values.toArray(new String[values.size()]));
    } else if (value.getClass().isArray()) {
        int n = Array.getLength(value);
        String results[] = new String[n];
        for (int i = 0; i < n; i++) {
            Object item = Array.get(value, i);
            if (item == null) {
                results[i] = null;
            } else {
                // convert to string using convert utils
                results[i] = getConvertUtils().convert(item);
            }
        }
        return (results);
    } else {
        String results[] = new String[1];
        results[0] = value.toString();
        return (results);
    }

}

From source file:javadz.beanutils.BeanUtilsBean.java

/**
 * Return the value of the specified array property of the specified
 * bean, as a String array./*from  w ww.  j av a  2s.com*/
 *
 * @param bean Bean whose property is to be extracted
 * @param name Name of the property to be extracted
 * @return The array property value
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 * @exception NoSuchMethodException if an accessor method for this
 *  property cannot be found
 */
public String[] getArrayProperty(Object bean, String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    Object value = getPropertyUtils().getProperty(bean, name);
    if (value == null) {
        return (null);
    } else if (value instanceof Collection) {
        ArrayList values = new ArrayList();
        Iterator items = ((Collection) value).iterator();
        while (items.hasNext()) {
            Object item = items.next();
            if (item == null) {
                values.add((String) null);
            } else {
                // convert to string using convert utils
                values.add(getConvertUtils().convert(item));
            }
        }
        return ((String[]) values.toArray(new String[values.size()]));
    } else if (value.getClass().isArray()) {
        int n = Array.getLength(value);
        String[] results = new String[n];
        for (int i = 0; i < n; i++) {
            Object item = Array.get(value, i);
            if (item == null) {
                results[i] = null;
            } else {
                // convert to string using convert utils
                results[i] = getConvertUtils().convert(item);
            }
        }
        return (results);
    } else {
        String[] results = new String[1];
        results[0] = getConvertUtils().convert(value);
        return (results);
    }

}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

private Object convertToTypedArray(Object input, String propertyName, Class<?> componentType) {
    if (input instanceof Collection) {
        // Convert Collection elements to array elements.
        Collection coll = (Collection) input;
        Object result = Array.newInstance(componentType, coll.size());
        int i = 0;
        for (Iterator it = coll.iterator(); it.hasNext(); i++) {
            Object value = convertIfNecessary(buildIndexedPropertyName(propertyName, i), null, it.next(),
                    componentType);//w  w w .  j  a  v  a2  s  . c o m
            Array.set(result, i, value);
        }
        return result;
    } else if (input.getClass().isArray()) {
        // Convert array elements, if necessary.
        if (componentType.equals(input.getClass().getComponentType())
                && !this.propertyEditorRegistry.hasCustomEditorForElement(componentType, propertyName)) {
            return input;
        }
        int arrayLength = Array.getLength(input);
        Object result = Array.newInstance(componentType, arrayLength);
        for (int i = 0; i < arrayLength; i++) {
            Object value = convertIfNecessary(buildIndexedPropertyName(propertyName, i), null,
                    Array.get(input, i), componentType);
            Array.set(result, i, value);
        }
        return result;
    } else {
        // A plain value: convert it to an array with a single component.
        Object result = Array.newInstance(componentType, 1);
        Object value = convertIfNecessary(buildIndexedPropertyName(propertyName, 0), null, input,
                componentType);
        Array.set(result, 0, value);
        return result;
    }
}

From source file:jef.database.DbUtils.java

/**
 * //from  w w w. ja  va  2  s.co  m
 * 
 * @param data
 *            
 * @param pk
 *            ?Map?
 */
public static void setPrimaryKeyValue(IQueryableEntity data, Object pk) throws PersistenceException {
    List<ColumnMapping> fields = MetaHolder.getMeta(data).getPKFields();
    if (fields.isEmpty())
        return;
    Assert.notNull(pk);
    // if (pk instanceof Map) {
    // Map<String, Object> pkMap = (Map<String, Object>) pk;
    // BeanWrapper wrapper = BeanWrapper.wrap(data, BeanWrapper.FAST);
    // for (Field f : fields) {
    // if (wrapper.isWritableProperty(f.name())) {
    // wrapper.setPropertyValue(f.name(), pkMap.get(f.name()));
    // }
    // }
    // } else
    if (pk.getClass().isArray()) {
        int length = Array.getLength(pk);
        int n = 0;
        Assert.isTrue(length == fields.size());
        for (ColumnMapping f : fields) {
            f.getFieldAccessor().set(data, Array.get(pk, n++));
        }
    } else {
        if (fields.size() != 1) {
            throw new PersistenceException("No Proper PK fields!");
        }
        fields.get(0).getFieldAccessor().set(data, pk);
    }
}

From source file:ArrayUtils.java

/**
 * Removes all contents of <code>array2</code> from <code>array1</code>. All
 * instances of <code>array2</code> will also be removed from
 * <code>array1</code>./*from w ww  .  ja  v a  2  s .c om*/
 * 
 * @param <T>
 *            The type of the array
 * @param array1
 *            The array to remove elements from
 * @param array2
 *            The array containing the elements to remove; or the element to
 *            remove itself
 * @return <code>array1</code> missing all the contents of
 *         <code>array2</code>
 */
public static <T> T[] removeAll(T[] array1, Object array2) {
    if (array1 == null || array2 == null)
        return array1;
    if (!array1.getClass().isArray())
        return null;
    if (!array2.getClass().isArray())
        array2 = new Object[] { array2 };
    java.util.BitSet remove = new java.util.BitSet();
    int len1 = array1.length;
    int len2 = Array.getLength(array2);
    int i, j;
    for (i = 0; i < len1; i++) {
        for (j = 0; j < len2; j++) {
            if (equals(array1[i], Array.get(array2, j))) {
                remove.set(i);
                break;
            }
        }
    }
    T[] ret = (T[]) Array.newInstance(array1.getClass().getComponentType(), len1 - remove.cardinality());
    // This copying section might be replaced by a more efficient version
    // using System.arraycopy()--this would be much faster than reflection,
    // especially for large arrays needing only a few elements removed
    for (i = 0, j = 0; i < len1; i++) {
        if (!remove.get(i)) {
            ret[j] = array1[i];
            j++;
        }
    }
    return ret;
}

From source file:org.eclipse.dataset.AbstractCompoundDataset.java

public static short[] toShortArray(final Object b, final int itemSize) {
    short[] result = null;

    if (b instanceof Number) {
        result = new short[itemSize];
        short val = ((Number) b).shortValue();
        for (int i = 0; i < itemSize; i++)
            result[i] = val;
    } else if (b instanceof short[]) {
        result = (short[]) b;
        if (result.length < itemSize) {
            result = new short[itemSize];
            int ilen = result.length;
            for (int i = 0; i < ilen; i++)
                result[i] = ((short[]) b)[i];
        }// www  .j  a va 2 s .  com
    } else if (b instanceof List<?>) {
        result = new short[itemSize];
        List<?> jl = (List<?>) b;
        int ilen = jl.size();
        if (ilen > 0 && !(jl.get(0) instanceof Number)) {
            logger.error("Given array was not of a numerical primitive type");
            throw new IllegalArgumentException("Given array was not of a numerical primitive type");
        }
        ilen = Math.min(itemSize, ilen);
        for (int i = 0; i < ilen; i++) {
            result[i] = (short) toLong(jl.get(i));
        }
    } else if (b.getClass().isArray()) {
        result = new short[itemSize];
        int ilen = Array.getLength(b);
        if (ilen > 0 && !(Array.get(b, 0) instanceof Number)) {
            logger.error("Given array was not of a numerical primitive type");
            throw new IllegalArgumentException("Given array was not of a numerical primitive type");
        }
        ilen = Math.min(itemSize, ilen);
        for (int i = 0; i < ilen; i++)
            result[i] = (short) ((Number) Array.get(b, i)).longValue();
    } else if (b instanceof Complex) {
        if (itemSize > 2) {
            logger.error("Complex number will not fit in compound dataset");
            throw new IllegalArgumentException("Complex number will not fit in compound dataset");
        }
        Complex cb = (Complex) b;
        switch (itemSize) {
        default:
        case 0:
            break;
        case 1:
            result = new short[] { (short) cb.getReal() };
            break;
        case 2:
            result = new short[] { (short) cb.getReal(), (short) cb.getImaginary() };
            break;
        }
    } else if (b instanceof Dataset) {
        Dataset db = (Dataset) b;
        if (db.getSize() != 1) {
            logger.error("Given dataset must have only one item");
            throw new IllegalArgumentException("Given dataset must have only one item");
        }
        return toShortArray(db.getObjectAbs(0), itemSize);
    } else if (b instanceof IDataset) {
        IDataset db = (Dataset) b;
        if (db.getSize() != 1) {
            logger.error("Given dataset must have only one item");
            throw new IllegalArgumentException("Given dataset must have only one item");
        }
        return toShortArray(db.getObject(new int[db.getRank()]), itemSize);
    }

    return result;
}

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

/**
 * <li><p> Call the property getter, if it exists.</p></li>
 * <p/>// www. j a v  a2s  .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:flex.messaging.services.http.proxy.RequestFilter.java

/**
 * Process the request body and return its content.
 *
 * @param context the context//from   ww w .  j  ava 2 s .  c  o  m
 * @return the body content
 */
protected Object processBody(ProxyContext context) {
    //FIXME: Should we also send on URL params that were used to contact the message broker servlet?

    Object body = context.getBody();
    if (body == null) {
        return "";
    } else if (body instanceof String) {
        return body;
    } else if (body instanceof Map) {
        Map params = (Map) body;

        StringBuffer postData = new StringBuffer();

        boolean formValues = false;
        for (Object entry : params.entrySet()) {
            String name = (String) ((Map.Entry) entry).getKey();
            if (!formValues) {
                formValues = true;
            } else {
                postData.append('&');
            }

            Object vals = ((Map.Entry) entry).getValue();

            if (vals == null) {
                encodeParam(postData, name, "");
            } else if (vals instanceof String) {
                String val = (String) vals;
                encodeParam(postData, name, val);
            } else if (vals instanceof List) {
                List valLists = (List) vals;

                for (int i = 0; i < valLists.size(); i++) {
                    Object o = valLists.get(i);
                    String val = "";
                    if (o != null)
                        val = o.toString();

                    if (i > 0)
                        postData.append('&');

                    encodeParam(postData, name, val);
                }
            } else if (vals.getClass().isArray()) {
                for (int i = 0; i < Array.getLength(vals); i++) {
                    Object o = Array.get(vals, i);
                    String val = "";
                    if (o != null)
                        val = o.toString();

                    if (i > 0)
                        postData.append('&');

                    encodeParam(postData, name, val);
                }
            }
        }

        return postData.toString();
    } else if (body.getClass().isArray()) {
        return body;
    } else if (body instanceof InputStream) {
        return body;
    } else {
        return body.toString();
    }
}