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.feilong.core.lang.ArrayUtil.java

/**
 *  <code>array</code>  <code>index</code> .
 * /*from   www . j av  a2  s. c o  m*/
 * <p>
 * (Returns the value of the indexed component in the specified array object. <br>
 * The value is automatically wrapped in an object if it has a primitive type.)
 * </p>
 * 
 * <pre class="code">
 * 
 * Example 1:
 * 
 * Object array = new String[] { "jinxin", "feilong", "1" };
 * LOGGER.info("" + ArrayUtil.getElement(array, 2));
 * 
 * :1
 * </pre>
 *
 * @param <T>
 *            the generic type
 * @param array
 *            
 * @param index
 *            
 * @return ?{@code index}, <code>array</code> , {@link ArrayIndexOutOfBoundsException}
 * @see java.lang.reflect.Array#get(Object, int)
 */
@SuppressWarnings("unchecked")
public static <T> T getElement(Object array, int index) {
    return (T) Array.get(array, index);
}

From source file:org.apache.bval.util.IndexedAccess.java

/**
 * {@inheritDoc}/*w w  w . ja  va  2 s.c  o m*/
 */
@Override
public Object get(Object instance) {
    if (index == null) {
        throw new UnsupportedOperationException("Cannot read null index");
    }
    if (instance != null && instance.getClass().isArray()) {
        if (Array.getLength(instance) - index > 0) {
            return Array.get(instance, index);
        }
    } else if (instance instanceof List<?>) {
        List<?> list = (List<?>) instance;
        if (list.size() - index > 0) {
            return list.get(index);
        }
    } else if (instance instanceof Iterable<?>) {
        int i = 0;
        for (Object o : (Iterable<?>) instance) {
            if (++i == index) {
                return o;
            }
        }
    }
    return null;
}

From source file:ArrayHelper.java

public static List toList(Object array) {
    if (array instanceof Object[])
        return Arrays.asList((Object[]) array); // faster?
    int size = Array.getLength(array);
    ArrayList list = new ArrayList(size);
    for (int i = 0; i < size; i++) {
        list.add(Array.get(array, i));
    }//from www. jav  a2s .  co m
    return list;
}

From source file:net.radai.beanz.codecs.ArrayCodec.java

@Override
public String encode(Object object) {
    if (object == null) {
        return null;
    }/*from   w w  w. ja  v  a 2s.  c o m*/
    if (!ReflectionUtil.isArray(object.getClass())) {
        throw new IllegalArgumentException();
    }
    int size = Array.getLength(object);
    if (size == 0) {
        return "[]";
    }
    StrBuilder sb = new StrBuilder();
    sb.append("[");
    for (int i = 0; i < size; i++) {
        Object element = Array.get(object, i);
        String encoded = elementCodec.encode(element);
        sb.append(encoded).append(", ");
    }
    sb.delete(sb.length() - 2, sb.length()); //last ", "
    sb.append("]");
    return sb.toString();
}

From source file:com.espertech.esper.epl.core.MethodPollingExecStrategy.java

public List<EventBean> poll(Object[] lookupValues) {
    List<EventBean> rowResult = null;
    try {/*from w ww  .ja v  a2s  .  co m*/
        Object invocationResult = method.invoke(null, lookupValues);
        if (invocationResult != null) {
            if (isArray) {
                int length = Array.getLength(invocationResult);
                if (length > 0) {
                    rowResult = new ArrayList<EventBean>();
                    for (int i = 0; i < length; i++) {
                        Object value = Array.get(invocationResult, i);
                        if (value == null) {
                            log.warn("Expected non-null return result from method '" + method.getName()
                                    + "', but received null value");
                            continue;
                        }

                        EventBean theEvent;
                        if (useMapType) {
                            if (!(value instanceof Map)) {
                                log.warn("Expected Map-type return result from method '" + method.getName()
                                        + "', but received type '" + value.getClass() + "'");
                                continue;
                            }
                            Map mapValues = (Map) value;
                            theEvent = eventAdapterService.adapterForTypedMap(mapValues, eventType);
                        } else {
                            theEvent = eventAdapterService.adapterForBean(value);
                        }

                        rowResult.add(theEvent);
                    }
                }
            } else {
                rowResult = new LinkedList<EventBean>();

                EventBean theEvent;
                if (useMapType) {
                    if (!(invocationResult instanceof Map)) {
                        log.warn("Expected Map-type return result from method '" + method.getName()
                                + "', but received type '" + invocationResult.getClass() + "'");
                    } else {
                        Map mapValues = (Map) invocationResult;
                        theEvent = eventAdapterService.adapterForTypedMap(mapValues, eventType);
                        rowResult.add(theEvent);
                    }
                } else {
                    theEvent = eventAdapterService.adapterForBean(invocationResult);
                    rowResult.add(theEvent);
                }
            }
        }
    } catch (InvocationTargetException ex) {
        throw new EPException("Method '" + method.getName() + "' of class '"
                + method.getJavaMethod().getDeclaringClass().getName() + "' reported an exception: "
                + ex.getTargetException(), ex.getTargetException());
    }

    return rowResult;
}

From source file:Main.java

/**
 * Returns the <code>index</code>-th value in <code>object</code>, throwing
 * <code>IndexOutOfBoundsException</code> if there is no such element or
 * <code>IllegalArgumentException</code> if <code>object</code> is not an
 * instance of one of the supported types.
 * <p/>/*  w ww. j a  va2  s.  c  o m*/
 * The supported types, and associated semantics are:
 * <ul>
 * <li> Map -- the value returned is the <code>Map.Entry</code> in position
 * <code>index</code> in the map's <code>entrySet</code> iterator,
 * if there is such an entry.</li>
 * <li> List -- this method is equivalent to the list's get method.</li>
 * <li> Array -- the <code>index</code>-th array entry is returned,
 * if there is such an entry; otherwise an <code>IndexOutOfBoundsException</code>
 * is thrown.</li>
 * <li> Collection -- the value returned is the <code>index</code>-th object
 * returned by the collection's default iterator, if there is such an element.</li>
 * <li> Iterator or Enumeration -- the value returned is the
 * <code>index</code>-th object in the Iterator/Enumeration, if there
 * is such an element.  The Iterator/Enumeration is advanced to
 * <code>index</code> (or to the end, if <code>index</code> exceeds the
 * number of entries) as a side effect of this method.</li>
 * </ul>
 *
 * @param object the object to get a value from
 * @param index  the index to get
 * @return the object at the specified index
 * @throws IndexOutOfBoundsException if the index is invalid
 * @throws IllegalArgumentException  if the object type is invalid
 */
public static Object get(Object object, int index) {
    if (index < 0)
        throw new IndexOutOfBoundsException("Index cannot be negative: " + index);

    if (object instanceof Map) {
        Map map = (Map) object;
        Iterator iterator = map.entrySet().iterator();
        return get(iterator, index);
    } else if (object instanceof List) {
        return ((List) object).get(index);
    } else if (object instanceof Object[]) {
        return ((Object[]) object)[index];
    } else if (object instanceof Iterator) {
        Iterator it = (Iterator) object;
        while (it.hasNext()) {
            index--;

            if (index == -1)
                return it.next();
            else
                it.next();
        }

        throw new IndexOutOfBoundsException("Entry does not exist: " + index);
    } else if (object instanceof Collection) {
        Iterator iterator = ((Collection) object).iterator();
        return get(iterator, index);
    } else if (object instanceof Enumeration) {
        Enumeration it = (Enumeration) object;
        while (it.hasMoreElements()) {
            index--;

            if (index == -1)
                return it.nextElement();
            else
                it.nextElement();
        }

        throw new IndexOutOfBoundsException("Entry does not exist: " + index);
    } else if (object == null) {
        throw new IllegalArgumentException("Unsupported object type: null");
    } else {
        try {
            return Array.get(object, index);
        } catch (IllegalArgumentException ex) {
            throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
        }
    }
}

From source file:org.kordamp.ezmorph.array.ByteArrayMorpher.java

public Object morph(Object array) {
    if (array == null) {
        return null;
    }/*from w ww  . j  a  va 2 s  .  co m*/

    if (BYTE_ARRAY_CLASS.isAssignableFrom(array.getClass())) {
        // no conversion needed
        return (byte[]) array;
    }

    if (array.getClass().isArray()) {
        int length = Array.getLength(array);
        int dims = getDimensions(array.getClass());
        int[] dimensions = createDimensions(dims, length);
        Object result = Array.newInstance(byte.class, dimensions);
        ByteMorpher morpher = isUseDefault() ? new ByteMorpher(defaultValue) : new ByteMorpher();
        if (dims == 1) {
            for (int index = 0; index < length; index++) {
                Array.set(result, index, morpher.morph(Array.get(array, index)));
            }
        } else {
            for (int index = 0; index < length; index++) {
                Array.set(result, index, morph(Array.get(array, index)));
            }
        }
        return result;
    } else {
        throw new MorphException("argument is not an array: " + array.getClass());
    }
}

From source file:org.openmrs.module.reportingrest.util.ParameterUtil.java

/**
 * Converts simple JSON types to the correct types as specified in _parameters_.
 *
 * This supports the scenario where a REST client submits a minimal representation of an object by looking up the
 * real object, and not just converting the submitted object's properties, e.g. you could submit an encounter type
 * that looks like {"display": "Emergency", "uuid": "07000be2-26b6-4cce-8b40-866d8435b613"} or even just
 * "07000be2-26b6-4cce-8b40-866d8435b613"
 *
 * @param parameters//from w  w w  .  j av  a  2s  . com
 * @param parameterValues
 * @return
 */
public static Map<String, Object> convertParameterValues(List<Parameter> parameters,
        Map<String, Object> parameterValues) throws Exception {
    if (parameterValues == null) {
        return null;
    }
    Map<String, Object> convertedParameterValues = new HashMap<String, Object>();
    for (Map.Entry<String, Object> entry : parameterValues.entrySet()) {
        Parameter parameter = findParameterByName(parameters, entry.getKey());
        if (parameter != null) {
            Resource resource = getResourceFor(parameter.getType());
            Object convertedValue;
            if (parameter.getCollectionType() != null) {
                Collection target = newCollectionFor(parameter);
                if (resource != null) {
                    // use the resource for this type, assuming a uuid for minimal representation was submitted
                    List original = (List) entry.getValue();
                    for (Object item : original) {
                        target.add(getRealInstanceByUuid(resource, item));
                    }
                    convertedValue = target;
                } else {
                    // no resource for this type, so it's probably a simple type (date, etc), and we use the REST
                    // module's ConversionUtil to convert it

                    // this looks hacky, but there's no good way to construct a ParameterizedType at run-time; the only
                    // way I know to programmatically construct something like a collection with type information is by
                    // using an array
                    Class<?> arrayClass = Array.newInstance(parameter.getType(), 0).getClass();
                    Object array = ConversionUtil.convert(entry.getValue(), arrayClass);

                    int length = Array.getLength(array);
                    for (int i = 0; i < length; ++i) {
                        target.add(Array.get(array, i));
                    }
                    convertedValue = target;
                }
            } else { // single value, not collection
                if (resource != null) {
                    // use the resource for this type, assuming a uuid for minimal representation was submitted
                    convertedValue = getRealInstanceByUuid(resource, entry.getValue());
                } else {
                    // no resource for this type, so it's probably a simple type (date, etc), and we use the REST
                    // module's ConversionUtil to convert it
                    convertedValue = ConversionUtil.convert(entry.getValue(), parameter.getType());
                }
            }

            convertedParameterValues.put(entry.getKey(), convertedValue);
        }
    }

    return convertedParameterValues;
}

From source file:de.tuberlin.uebb.jbop.optimizer.array.LocalArrayLengthInliner.java

@Override
protected boolean handleValues(final InsnList original, final Map<Integer, Object> knownArrays,
        final AbstractInsnNode currentNode) {
    if (!NodeHelper.isArrayLength(currentNode)) {
        return false;
    }/*www  .j a v  a  2 s  .c o m*/

    AbstractInsnNode previous = NodeHelper.getPrevious(currentNode);
    final List<AbstractInsnNode> toBeRemoved = new ArrayList<>();
    int index2 = 0;
    while ((previous != null) && !NodeHelper.isAload(previous)) {
        if (NodeHelper.isAAload(previous)) {
            index2 += 1;
        }
        toBeRemoved.add(previous);
        previous = NodeHelper.getPrevious(previous);
    }
    final int index;
    if ((previous != null) && NodeHelper.isAload(previous)) {
        toBeRemoved.add(previous);
        index = ((VarInsnNode) previous).var;
    } else {
        return false;
    }

    final Object array = knownArrays.get(Integer.valueOf(index));
    if ((array == null)) {
        return false;
    }
    Object array2 = array;
    for (int i = 0; i < index2; ++i) {
        array2 = Array.get(array2, i);
    }
    final int arrayLength = Array.getLength(array2);
    original.insertBefore(currentNode, NodeHelper.getInsnNodeFor(arrayLength));

    for (final AbstractInsnNode remove : toBeRemoved) {
        original.remove(remove);
    }
    original.remove(currentNode);
    return true;
}

From source file:org.kordamp.ezmorph.array.IntArrayMorpher.java

public Object morph(Object array) {
    if (array == null) {
        return null;
    }//from   ww  w .  ja  v a2  s  .c  o m

    if (INT_ARRAY_CLASS.isAssignableFrom(array.getClass())) {
        // no conversion needed
        return (int[]) array;
    }

    if (array.getClass().isArray()) {
        int length = Array.getLength(array);
        int dims = getDimensions(array.getClass());
        int[] dimensions = createDimensions(dims, length);
        Object result = Array.newInstance(int.class, dimensions);
        IntMorpher morpher = isUseDefault() ? new IntMorpher(defaultValue) : new IntMorpher();
        if (dims == 1) {
            for (int index = 0; index < length; index++) {
                Array.set(result, index, morpher.morph(Array.get(array, index)));
            }
        } else {
            for (int index = 0; index < length; index++) {
                Array.set(result, index, morph(Array.get(array, index)));
            }
        }
        return result;
    } else {
        throw new MorphException("argument is not an array: " + array.getClass());
    }
}