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:org.eclipse.dataset.AbstractDataset.java

/**
 * Get shape from object//  w ww . ja  va  2s.  c  om
 * @param ldims
 * @param obj
 * @param depth
 * @return true if there is a possibility of differing lengths
 */
private static boolean getShapeFromObj(final ArrayList<Integer> ldims, Object obj, int depth) {
    if (obj == null)
        return true;

    if (obj instanceof List<?>) {
        List<?> jl = (List<?>) obj;
        int l = jl.size();
        updateShape(ldims, depth, l);
        for (int i = 0; i < l; i++) {
            Object lo = jl.get(i);
            if (!getShapeFromObj(ldims, lo, depth + 1)) {
                break;
            }
        }
        return true;
    }
    Class<? extends Object> ca = obj.getClass().getComponentType();
    if (ca != null) {
        final int l = Array.getLength(obj);
        updateShape(ldims, depth, l);
        if (isComponentSupported(ca)) {
            return true;
        }
        for (int i = 0; i < l; i++) {
            Object lo = Array.get(obj, i);
            if (!getShapeFromObj(ldims, lo, depth + 1)) {
                break;
            }
        }
        return true;
    } else if (obj instanceof IDataset) {
        int[] s = ((IDataset) obj).getShape();
        for (int i = 0; i < s.length; i++) {
            updateShape(ldims, depth++, s[i]);
        }
        return true;
    } else {
        return false; // not an array of any type
    }
}

From source file:org.opensha.commons.util.DataUtils.java

/**
 * Creates a new array from the values in a source array at the specified
 * indices. Returned array is of same type as source.
 * //w  ww.  j  av a2  s  .  c  om
 * @param array array source
 * @param indices index values of items to select
 * @return a new array of values at indices in source
 * @throws NullPointerException if {@code array} or
 *         {@code indices} are {@code null}
 * @throws IllegalArgumentException if data object is not an array or if
 *         data array is empty
 * @throws IndexOutOfBoundsException if any indices are out of range
 */
public static Object arraySelect(Object array, int[] indices) {
    checkNotNull(array, "Supplied data array is null");
    checkNotNull(indices, "Supplied index array is null");
    checkArgument(array.getClass().isArray(), "Data object supplied is not an array");
    int arraySize = Array.getLength(array);
    checkArgument(arraySize != 0, "Supplied data array is empty");

    // validate indices
    for (int i = 0; i < indices.length; i++) {
        checkPositionIndex(indices[i], arraySize, "Supplied index");
    }

    Class<? extends Object> srcClass = array.getClass().getComponentType();
    Object out = Array.newInstance(srcClass, indices.length);
    for (int i = 0; i < indices.length; i++) {
        Array.set(out, i, Array.get(array, indices[i]));
    }
    return out;
}

From source file:org.eclipse.wb.tests.designer.core.util.ast.BindingsTest.java

private static void assert_equals(Method method, Object expectedValue, Object actualValue) {
    String message = "For method " + method;
    if (expectedValue == null) {
        assertNull(message, actualValue);
    } else if (expectedValue.getClass().isArray()) {
        assertTrue(message, actualValue.getClass().isArray());
        int length = Array.getLength(expectedValue);
        for (int i = 0; i < length; i++) {
            Object expectedElement = Array.get(expectedValue, i);
            Object actualElement = Array.get(actualValue, i);
            assert_equals(method, expectedElement, actualElement);
        }/*from  w  w w .  ja  v a 2 s .c o m*/
    } else if (expectedValue instanceof IMethodBinding) {
        assertEquals(getMethodSignature((IMethodBinding) expectedValue),
                getMethodSignature((IMethodBinding) actualValue));
    } else if (expectedValue instanceof ITypeBinding) {
        assertEquals(getFullyQualifiedName((ITypeBinding) expectedValue, false),
                getFullyQualifiedName((ITypeBinding) actualValue, false));
    } else if (expectedValue instanceof IPackageBinding) {
        IPackageBinding expectedPackage = (IPackageBinding) expectedValue;
        IPackageBinding actualPackage = (IPackageBinding) actualValue;
        assertEquals(message, expectedPackage.getName(), actualPackage.getName());
        assertEquals(message, expectedPackage.isUnnamed(), actualPackage.isUnnamed());
    } else {
        assertEquals(message, expectedValue, actualValue);
    }
}

From source file:ArrayUtils.java

/**
 * Searches an array (possibly primitive) for an element
 * //from  w  ww  .j av a2 s  . c o m
 * @param anArray
 *            The array to search
 * @param anElement
 *            The element to search for
 * @return True if <code>anArray</code> contains <code>anElement</code>,
 *         false otherwise
 */
public static boolean containsP(Object anArray, Object anElement) {
    if (anArray == null)
        return false;
    if (anArray instanceof Object[]) {
        Object[] oa = (Object[]) anArray;
        for (int i = 0; i < oa.length; i++) {
            if (equals(oa[i], anElement))
                return true;
        }
    } else {
        int len = Array.getLength(anArray);
        for (int i = 0; i < len; i++) {
            if (equals(Array.get(anArray, i), anElement))
                return true;
        }
    }
    return false;
}

From source file:org.crank.javax.faces.component.MenuRenderer.java

boolean isSelected(Object itemValue, Object valueArray) {

    if (null != valueArray) {
        if (!valueArray.getClass().isArray()) {
            logger.warning("valueArray is not an array, the actual type is " + valueArray.getClass());
            return valueArray.equals(itemValue);
        }//from  w  ww .j a va 2  s.  c om
        int len = Array.getLength(valueArray);
        for (int i = 0; i < len; i++) {
            Object value = Array.get(valueArray, i);
            if (value == null) {
                if (itemValue == null) {
                    return true;
                }
            } else if (value.equals(itemValue)) {
                return true;
            }
        }
    }
    return false;

}

From source file:microsoft.exchange.webservices.data.property.complex.UserConfigurationDictionary.java

/**
 * Validates the dictionary object (key or entry value).
 *
 * @param dictionaryObject Object to validate.
 * @throws Exception the exception//w w w  .  ja  v  a  2  s . c om
 */
private void validateObject(Object dictionaryObject) throws Exception {
    // Keys may not be null but we rely on the internal dictionary to throw
    // if the key is null.
    if (dictionaryObject != null) {
        if (dictionaryObject.getClass().isArray()) {
            int length = Array.getLength(dictionaryObject);
            Class<?> wrapperType = Array.get(dictionaryObject, 0).getClass();
            Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
            for (int i = 0; i < length; i++) {
                newArray[i] = Array.get(dictionaryObject, i);
            }
            this.validateArrayObject(newArray);
        } else {
            this.validateObjectType(dictionaryObject);

        }

    } else {
        throw new NullPointerException();
    }
}

From source file:com.comphenix.protocol.events.PacketContainerTest.java

/**
 * Get the underlying array as an object array.
 * @param val - array wrapped as an Object.
 * @return An object array./*from   w  w  w.  j  a v a 2s  . c  o  m*/
 */
private Object[] getArray(Object val) {
    if (val instanceof Object[])
        return (Object[]) val;
    if (val == null)
        return null;

    int arrlength = Array.getLength(val);
    Object[] outputArray = new Object[arrlength];

    for (int i = 0; i < arrlength; ++i)
        outputArray[i] = Array.get(val, i);
    return outputArray;
}

From source file:com.zenesis.qx.remote.RequestHandler.java

/**
 * Handles dynamic changes to a qa.data.Array instance without having a complete replacement; expects a 
 * serverId, propertyName, type (one of "add", "remove", "order"), start, end, and optional array of items 
 * @param jp/* w  w  w  .j a v a  2s . co  m*/
 * @throws ServletException
 * @throws IOException
 */
protected void cmdEditArray(JsonParser jp) throws ServletException, IOException {
    // Get the basics
    int serverId = getFieldValue(jp, "serverId", Integer.class);
    String propertyName = getFieldValue(jp, "propertyName", String.class);
    String action = getFieldValue(jp, "type", String.class);
    Integer start = null;
    Integer end = null;

    if (!action.equals("replaceAll")) {
        start = getFieldValue(jp, "start", Integer.class);
        end = getFieldValue(jp, "end", Integer.class);
    }

    // Get our info
    Proxied serverObject = getProxied(serverId);
    ProxyType type = ProxyTypeManager.INSTANCE.getProxyType(serverObject.getClass());
    ProxyProperty prop = getProperty(type, propertyName);

    if (prop.getPropertyClass().isMap()) {
        Map items = null;

        // Get the optional array of items
        if (jp.nextToken() == JsonToken.FIELD_NAME && jp.getCurrentName().equals("items")
                && jp.nextToken() == JsonToken.START_OBJECT) {

            items = readMap(jp, prop.getPropertyClass().getKeyClass(), prop.getPropertyClass().getJavaType());
        }

        // Quick logging
        if (log.isInfoEnabled()) {
            String str = "";
            if (items != null)
                for (Object key : items.keySet()) {
                    if (str.length() > 0)
                        str += ", ";
                    str += String.valueOf(key) + "=" + String.valueOf(items.get(key));
                }
            log.info("edit-array: property=" + prop + ", type=" + action + ", start=" + start + ", end=" + end
                    + str);
        }

        if (action.equals("replaceAll")) {
            Map map = (Map) prop.getValue(serverObject);
            if (map == null) {
                try {
                    map = (Map) prop.getPropertyClass().getCollectionClass().newInstance();
                } catch (Exception e) {
                    throw new IllegalArgumentException(e.getMessage(), e);
                }
                prop.setValue(serverObject, map);
            }
            map.clear();
            map.putAll(items);
        } else
            throw new IllegalArgumentException("Unsupported action in cmdEditArray: " + action);

        // Because collection properties are objects and we change them without the serverObject's
        //   knowledge, we have to make sure we notify other trackers ourselves
        ProxyManager.propertyChanged(serverObject, propertyName, items, null);

        jp.nextToken();
    } else {
        // NOTE: items is an Array!!  But because it may be an array of primitive types, we have
        //   to use java.lang.reflect.Array to access members because we cannot cast arrays of
        //   primitives to Object[]
        Object items = null;

        // Get the optional array of items
        if (jp.nextToken() == JsonToken.FIELD_NAME && jp.getCurrentName().equals("items")
                && jp.nextToken() == JsonToken.START_ARRAY) {

            items = readArray(jp, prop.getPropertyClass().getJavaType());
        }
        int itemsLength = Array.getLength(items);

        // Quick logging
        if (log.isInfoEnabled()) {
            String str = "";
            if (items != null)
                for (int i = 0; i < itemsLength; i++) {
                    if (str.length() != 0)
                        str += ", ";
                    str += Array.get(items, i);
                }
            log.info("edit-array: property=" + prop + ", type=" + action + ", start=" + start + ", end=" + end
                    + str);
        }

        if (action.equals("replaceAll")) {
            if (prop.getPropertyClass().isCollection()) {
                Collection list = (Collection) prop.getValue(serverObject);
                if (list == null) {
                    try {
                        list = (Collection) prop.getPropertyClass().getCollectionClass().newInstance();
                    } catch (Exception e) {
                        throw new IllegalArgumentException(e.getMessage(), e);
                    }
                    prop.setValue(serverObject, list);
                }
                list.clear();
                if (items != null)
                    for (int i = 0; i < itemsLength; i++)
                        list.add(Array.get(items, i));

                // Because collection properties are objects and we change them without the serverObject's
                //   knowledge, we have to make sure we notify other trackers ourselves
                ProxyManager.propertyChanged(serverObject, propertyName, list, null);
            } else {
                prop.setValue(serverObject, items);
            }
        } else
            throw new IllegalArgumentException("Unsupported action in cmdEditArray: " + action);

        jp.nextToken();
    }
}

From source file:ArrayUtils.java

/**
 * Like {@link #containsP(Object, Object)} but the equality test is by
 * identity instead of the equals method
 * /*from   ww w .  j  a  v  a  2 s. co m*/
 * @param anArray
 *            The array to search
 * @param anElement
 *            The element to search for
 * @return True if <code>anArray</code> contains <code>anElement</code> by
 *         identity, false otherwise
 */
public static boolean containspID(Object anArray, Object anElement) {
    if (anArray == null)
        return false;
    if (anArray instanceof Object[]) {
        Object[] oa = (Object[]) anArray;
        for (int i = 0; i < oa.length; i++) {
            if (oa[i] == anElement)
                return true;
        }
    } else {
        int len = Array.getLength(anArray);
        for (int i = 0; i < len; i++) {
            if (Array.get(anArray, i) == anElement)
                return true;
        }
    }
    return false;
}

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

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

    if (b instanceof Number) {
        result = new byte[itemSize];
        final byte val = ((Number) b).byteValue();
        for (int i = 0; i < itemSize; i++)
            result[i] = val;
    } else if (b instanceof byte[]) {
        result = (byte[]) b;
        if (result.length < itemSize) {
            result = new byte[itemSize];
            int ilen = result.length;
            for (int i = 0; i < ilen; i++)
                result[i] = ((byte[]) b)[i];
        }/*www  .  ja  v a  2s.  com*/
    } else if (b instanceof List<?>) {
        result = new byte[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] = (byte) toLong(jl.get(i));
        }
    } else if (b.getClass().isArray()) {
        result = new byte[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] = (byte) ((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 byte[] { (byte) cb.getReal() };
            break;
        case 2:
            result = new byte[] { (byte) cb.getReal(), (byte) 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 toByteArray(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 toByteArray(db.getObject(new int[db.getRank()]), itemSize);
    }

    return result;
}