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.jgentleframework.utils.ObjectUtils.java

/**
 * Convert the given array (which may be a primitive array) to an object
 * array (if necessary of primitive wrapper objects).
 * <p>/*from ww w.j a v a2  s .  c om*/
 * A <code>null</code> source value will be converted to an empty Object
 * array.
 * 
 * @param source
 *            the (potentially primitive) array
 * @return the corresponding object array (never <code>null</code>)
 * @throws IllegalArgumentException
 *             if the parameter is not an array
 */
public static Object[] toObjectArray(Object source) {

    if (source instanceof Object[]) {
        return (Object[]) source;
    }
    if (source == null) {
        return new Object[0];
    }
    if (!source.getClass().isArray()) {
        throw new IllegalArgumentException("Source is not an array: " + source);
    }
    int length = Array.getLength(source);
    if (length == 0) {
        return new Object[0];
    }
    Class<?> wrapperType = Array.get(source, 0).getClass();
    Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
    for (int i = 0; i < length; i++) {
        newArray[i] = Array.get(source, i);
    }
    return newArray;
}

From source file:com.astamuse.asta4d.web.form.flow.base.AbstractFormFlowSnippet.java

/**
 * /*from w  w  w. j a  v  a  2s . co  m*/
 * Render the value of all the given form's fields.The rendering of cascade forms will be done here as well(recursively call the
 * {@link #renderForm(String, Object, int)}).
 * 
 * @param renderTargetStep
 * @param form
 * @param cascadeFormArrayIndex
 * @return
 * @throws Exception
 */
private Renderer renderValueOfFields(String renderTargetStep, Object form, int cascadeFormArrayIndex)
        throws Exception {
    Renderer render = Renderer.create();
    List<AnnotatedPropertyInfo> fieldList = AnnotatedPropertyUtil.retrieveProperties(form.getClass());

    for (AnnotatedPropertyInfo field : fieldList) {

        Object v = field.retrieveValue(form);

        CascadeFormField cff = field.getAnnotation(CascadeFormField.class);
        if (cff != null) {
            String containerSelector = cff.containerSelector();

            if (field.getType().isArray()) {// a cascade form for array
                int len = Array.getLength(v);
                List<Renderer> subRendererList = new ArrayList<>(len);
                int loopStart = 0;
                if (renderForEdit(renderTargetStep, form, cff.name())) {
                    // for rendering a template DOM
                    loopStart = -1;
                }
                Class<?> subFormType = field.getType().getComponentType();
                Object subForm;
                for (int i = loopStart; i < len; i++) {
                    // retrieve the form instance
                    if (i >= 0) {
                        subForm = Array.get(v, i);
                    } else {
                        // create a template instance
                        subForm = createFormInstanceForCascadeFormArrayTemplate(subFormType);
                    }

                    Renderer subRenderer = Renderer.create();

                    // only rewrite the refs for normal instances
                    if (i >= 0) {
                        // subRenderer.add(setCascadeFormContainerArrayRef(i));
                        subRenderer.add(rewriteCascadeFormFieldArrayRef(renderTargetStep, subForm, i));
                    }

                    subRenderer.add(renderForm(renderTargetStep, subForm, i));

                    // hide the template DOM
                    if (i < 0) {
                        subRenderer.add(":root", hideCascadeFormTemplateDOM(subFormType));
                    }

                    subRendererList.add(subRenderer);
                }
                render.add(containerSelector, subRendererList);
            } else {// a simple cascade form

                if (StringUtils.isNotEmpty(containerSelector)) {
                    render.add(containerSelector, renderForm(renderTargetStep, v, -1));
                } else {
                    render.add(renderForm(renderTargetStep, v, -1));
                }
            }
            continue;
        }

        if (v == null) {
            @SuppressWarnings("rawtypes")
            ContextDataHolder valueHolder;

            if (field.getField() != null) {
                valueHolder = InjectTrace.getInstanceInjectionTraceInfo(form, field.getField());
            } else {
                valueHolder = InjectTrace.getInstanceInjectionTraceInfo(form, field.getSetter());
            }

            if (valueHolder != null) {
                v = convertRawInjectionTraceDataToRenderingData(field.getName(), field.getType(),
                        valueHolder.getFoundOriginalData());
            }
        }

        FieldRenderingInfo renderingInfo = getRenderingInfo(field, cascadeFormArrayIndex);

        // render.addDebugger("whole form before: " + field.getName());

        if (renderForEdit(renderTargetStep, form, field.getName())) {
            render.add(renderingInfo.valueRenderer.renderForEdit(renderingInfo.editSelector, v));
        } else {
            render.add(renderingInfo.valueRenderer.renderForDisplay(renderingInfo.editSelector,
                    renderingInfo.displaySelector, v));
        }
    }
    return render;
}

From source file:org.jolokia.client.request.J4pRequest.java

private Object serializeArray(Object pArg) {
    JSONArray innerArray = new JSONArray();
    for (int i = 0; i < Array.getLength(pArg); i++) {
        innerArray.add(serializeArgumentToJson(Array.get(pArg, i)));
    }//from w  w  w.  ja  v a2  s .  c  o m
    return innerArray;
}

From source file:com.astamuse.asta4d.data.DefaultDataTypeTransformer.java

private List<DataValueConvertor> extractConvertors(final Class<?> srcType, final Class<?> targetType) {

    List<DataValueConvertor> foundConvertorList = new LinkedList<DataValueConvertor>();

    // find in list as element to element
    for (DataValueConvertor convertor : DataTypeConvertorList) {
        Pair<Class, Class> typePair = extractConvertorTypeInfo(convertor);
        if (typePair == null) {
            continue;
        }/*ww  w  .  j a  v  a 2s  .  c o m*/
        if (typePair.getLeft().isAssignableFrom(srcType)) {
            if (targetType.isAssignableFrom(typePair.getRight())) {// found one
                foundConvertorList.add(convertor);
            } else if (convertor instanceof DataValueConvertorTargetTypeConvertable
                    && typePair.getRight().isAssignableFrom(targetType)) {
                foundConvertorList
                        .add(((DataValueConvertorTargetTypeConvertable) convertor).convert(targetType));
            }
        }
        // @formatter:on
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    // find as array to array
    if (srcType.isArray() && targetType.isArray()) {

        List<DataValueConvertor> componentConvertorList = findConvertor(srcType.getComponentType(),
                targetType.getComponentType());
        List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList,
                new RowConvertor<DataValueConvertor, DataValueConvertor>() {
                    @Override
                    public DataValueConvertor convert(int rowIndex,
                            final DataValueConvertor originalConvertor) {
                        return new DataValueConvertor() {
                            Pair<Class, Class> typePair = extractConvertorTypeInfo(originalConvertor);

                            @Override
                            public Object convert(Object obj) throws UnsupportedValueException {
                                if (typePair == null) {
                                    return null;
                                }

                                int length = Array.getLength(obj);
                                Object targetArray = Array.newInstance(targetType.getComponentType(), length);

                                for (int i = 0; i < length; i++) {
                                    Array.set(targetArray, i, originalConvertor.convert(Array.get(obj, i)));
                                }
                                return targetArray;
                            }
                        };
                    }
                });

        foundConvertorList.addAll(toArrayConvertorList);
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    // find as element to array
    if (targetType.isArray()) {

        List<DataValueConvertor> componentConvertorList = findConvertor(srcType, targetType.getComponentType());
        List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList,
                new RowConvertor<DataValueConvertor, DataValueConvertor>() {
                    @Override
                    public DataValueConvertor convert(int rowIndex,
                            final DataValueConvertor originalConvertor) {
                        return new DataValueConvertor() {
                            private Pair<Class, Class> typePair = extractConvertorTypeInfo(originalConvertor);

                            @Override
                            public Object convert(Object obj) throws UnsupportedValueException {
                                if (typePair == null) {
                                    return null;
                                }
                                Object array = Array.newInstance(targetType.getComponentType(), 1);
                                Array.set(array, 0, originalConvertor.convert(obj));
                                return array;
                            }
                        };
                    }
                });

        foundConvertorList.addAll(toArrayConvertorList);
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    // find as array to element
    if (srcType.isArray()) {
        List<DataValueConvertor> componentConvertorList = findConvertor(srcType.getComponentType(), targetType);
        List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList,
                new RowConvertor<DataValueConvertor, DataValueConvertor>() {
                    @Override
                    public DataValueConvertor convert(int rowIndex,
                            final DataValueConvertor originalConvertor) {
                        return new DataValueConvertor() {
                            @Override
                            public Object convert(Object obj) throws UnsupportedValueException {
                                int length = Array.getLength(obj);
                                if (length == 0) {
                                    return null;
                                } else {
                                    return originalConvertor.convert(Array.get(obj, 0));
                                }
                            }
                        };
                    }
                });

        foundConvertorList.addAll(toArrayConvertorList);
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    return foundConvertorList;
}

From source file:org.apache.struts.taglib.logic.IterateTag.java

/**
 * Construct an iterator for the specified collection, and begin
 * looping through the body once per element.
 *
 * @exception JspException if a JSP exception has occurred
 *///from w  w  w  .  j  a  v a  2  s  .c o m
public int doStartTag() throws JspException {

    // Acquire the collection we are going to iterate over
    Object collection = this.collection;
    if (collection == null) {
        collection = RequestUtils.lookup(pageContext, name, property, scope);
    }

    if (collection == null) {
        JspException e = new JspException(messages.getMessage("iterate.collection"));
        RequestUtils.saveException(pageContext, e);
        throw e;
    }

    // Construct an iterator for this collection
    if (collection.getClass().isArray()) {
        try {
            // If we're lucky, it is an array of objects
            // that we can iterate over with no copying
            iterator = Arrays.asList((Object[]) collection).iterator();
        } catch (ClassCastException e) {
            // Rats -- it is an array of primitives
            int length = Array.getLength(collection);
            ArrayList c = new ArrayList(length);
            for (int i = 0; i < length; i++) {
                c.add(Array.get(collection, i));
            }
            iterator = c.iterator();
        }
    } else if (collection instanceof Collection) {
        iterator = ((Collection) collection).iterator();
    } else if (collection instanceof Iterator) {
        iterator = (Iterator) collection;
    } else if (collection instanceof Map) {
        iterator = ((Map) collection).entrySet().iterator();
    } else if (collection instanceof Enumeration) {
        iterator = IteratorUtils.asIterator((Enumeration) collection);
    } else {
        JspException e = new JspException(messages.getMessage("iterate.iterator"));
        RequestUtils.saveException(pageContext, e);
        throw e;
    }

    // Calculate the starting offset
    if (offset == null) {
        offsetValue = 0;
    } else {
        try {
            offsetValue = Integer.parseInt(offset);
        } catch (NumberFormatException e) {
            Integer offsetObject = (Integer) RequestUtils.lookup(pageContext, offset, null);
            if (offsetObject == null) {
                offsetValue = 0;
            } else {
                offsetValue = offsetObject.intValue();
            }
        }
    }
    if (offsetValue < 0) {
        offsetValue = 0;
    }

    // Calculate the rendering length
    if (length == null) {
        lengthValue = 0;
    } else {
        try {
            lengthValue = Integer.parseInt(length);
        } catch (NumberFormatException e) {
            Integer lengthObject = (Integer) RequestUtils.lookup(pageContext, length, null);
            if (lengthObject == null) {
                lengthValue = 0;
            } else {
                lengthValue = lengthObject.intValue();
            }
        }
    }
    if (lengthValue < 0) {
        lengthValue = 0;
    }
    lengthCount = 0;

    // Skip the leading elements up to the starting offset
    for (int i = 0; i < offsetValue; i++) {
        if (iterator.hasNext()) {
            iterator.next();
        }
    }

    // Store the first value and evaluate, or skip the body if none
    if (iterator.hasNext()) {
        Object element = iterator.next();
        if (element == null) {
            pageContext.removeAttribute(id);
        } else {
            pageContext.setAttribute(id, element);
        }
        lengthCount++;
        started = true;
        if (indexId != null) {
            pageContext.setAttribute(indexId, new Integer(getIndex()));
        }
        return (EVAL_BODY_TAG);
    } else {
        return (SKIP_BODY);
    }

}

From source file:org.formix.dsx.builders.XmlBuilder.java

private void addArrayItemNodes(XmlElement root, Object obj, Class<?> type) throws XmlException {
    if (type.isArray()) {
        for (int i = 0; i < Array.getLength(obj); i++) {
            Object item = Array.get(obj, i);
            XmlContent content = this.createXml(item, null);
            root.addChild(content);/*from   w w w. ja  va2 s.c o  m*/
        }
    } else {
        Collection<?> elements = (Collection<?>) obj;
        for (Object element : elements) {
            XmlContent content = this.createXml(element, null);
            root.addChild(content);
        }
    }
}

From source file:org.crazydog.util.spring.ObjectUtils.java

/**
 * Convert the given array (which may be a primitive array) to an
 * object array (if necessary of primitive wrapper objects).
 * <p>A {@code null} source value will be converted to an
 * empty Object array./*from  w ww . j  a  v  a 2s .  c  o  m*/
 * @param source the (potentially primitive) array
 * @return the corresponding object array (never {@code null})
 * @throws IllegalArgumentException if the parameter is not an array
 */
public static Object[] toObjectArray(Object source) {
    if (source instanceof Object[]) {
        return (Object[]) source;
    }
    if (source == null) {
        return new Object[0];
    }
    if (!source.getClass().isArray()) {
        throw new IllegalArgumentException("Source is not an array: " + source);
    }
    int length = Array.getLength(source);
    if (length == 0) {
        return new Object[0];
    }
    Class<?> wrapperType = Array.get(source, 0).getClass();
    Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
    for (int i = 0; i < length; i++) {
        newArray[i] = Array.get(source, i);
    }
    return newArray;
}

From source file:org.ebayopensource.common.util.DataUtil.java

public static int[] getIntArray(Object object, int[] defValue) {
    if (object == null) {
        return defValue;
    }/* ww w  . ja  v  a  2  s.  c  om*/

    int[] result;
    if (object instanceof int[]) {
        result = (int[]) object;
    } else if (object instanceof Number) {
        result = new int[] { getInt(object, 0) };
    } else if (object instanceof Number[]) {
        Number[] array = (Number[]) object;
        result = new int[array.length];
        for (int i = 0; i < array.length; i++) {
            result[i] = array[i].intValue();
        }
    } else if (object.getClass().isArray()) {
        int len = Array.getLength(object);
        result = new int[len];
        for (int i = 0; i < len; i++) {
            result[i] = getInt(Array.get(object, i), 0);
        }
    } else if (object instanceof Boolean) {
        result = new int[] { getInt(object, 0) };
    } else {
        result = defValue;
    }
    return result;
}

From source file:org.jaxygen.converters.properties.PropertiesToBeanConverter.java

private static void fillBeanArrayField(final String name, Object value, Object bean, BeanInfo beanInfo,
        String[] path, final String fieldName, int bracketStart, int len)
        throws IllegalAccessException, InvocationTargetException, IntrospectionException,
        InstantiationException, IllegalArgumentException, WrongProperyIndex {
    final String indexStr = fieldName.substring(bracketStart + 1, len - 1);
    final String propertyName = fieldName.substring(0, bracketStart);
    int index = Integer.parseInt(indexStr);
    String childName = "";
    int firstDot = name.indexOf(".");
    if (firstDot > 0) {
        childName = name.substring(firstDot + 1);
    }//from   w ww.  j  a v a 2s  .  c o m

    for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
        if (pd.getName().equals(propertyName)) {
            Method writter = pd.getWriteMethod();
            Method reader = pd.getReadMethod();
            if (writter != null && reader != null) {
                Object array = reader.invoke(bean);
                if (pd.getPropertyType().isArray()) {
                    if (array == null) {
                        array = Array.newInstance(pd.getPropertyType().getComponentType(), index + 1);
                        writter.invoke(bean, array);
                    }
                    if (Array.getLength(array) < (index + 1)) {
                        array = resizeArray(array, index + 1);
                        writter.invoke(bean, array);
                    }
                    if (path.length == 1) {
                        Object valueObject = parsePropertyToValue(value, array.getClass().getComponentType());
                        Array.set(array, index, valueObject);
                    } else {
                        Object valueObject = fillBeanValueByName(childName, value,
                                array.getClass().getComponentType(), Array.get(array, index));
                        Array.set(array, index, valueObject);
                    }
                } else if (pd.getPropertyType().equals(List.class)) {
                    if (array == null) {
                        array = pd.getPropertyType().newInstance();
                        writter.invoke(bean, array);
                    }
                    Class<?> genericClass = array.getClass().getTypeParameters()[0].getClass();
                    if (path.length == 1) {
                        Object valueObject = parsePropertyToValue(value, genericClass);
                        Array.set(array, index, valueObject);
                    } else {
                        Object valueObject = fillBeanValueByName(childName, value, genericClass, null);
                        Array.set(array, index, valueObject);
                    }
                }
            }
        }
    }
}

From source file:com.googlecode.aviator.runtime.type.AviatorJavaType.java

/**
 * Access array or list element//from  w w w  .  ja  v  a  2  s.  c o  m
 * 
 * @param env
 * @param indexObject
 * @return
 */
@SuppressWarnings("unchecked")
public AviatorObject getElement(Map<String, Object> env, AviatorObject indexObject) {
    Object thisValue = getValue(env);
    if (!thisValue.getClass().isArray() && !(thisValue instanceof List)) {
        throw new ExpressionRuntimeException(
                this.desc(env) + " is not a array or list,could not use [] to get element");
    }
    Object indexValue = indexObject.getValue(env);
    if (!isInteger(indexValue)) {
        throw new IllegalArgumentException("Illegal index " + indexObject.desc(env));
    }
    int index = ((Number) indexValue).intValue();
    if (thisValue.getClass().isArray()) {
        return new AviatorRuntimeJavaType(Array.get(thisValue, index));
    } else {
        return new AviatorRuntimeJavaType(((List) thisValue).get(index));
    }
}