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.kuali.rice.krad.uif.lifecycle.ViewLifecycleUtils.java

/**
 * Gets subcomponents for lifecycle processing.
 *
 * @param element The component to scan.
 * @param viewPhase The view phase to return subcomponents for.
 * @return lifecycle components//from  w w  w  . j a va2  s  .co  m
 */
public static Map<String, LifecycleElement> getElementsForLifecycle(LifecycleElement element,
        String viewPhase) {
    if (element == null) {
        return Collections.emptyMap();
    }

    Set<String> nestedElementProperties = ObjectPropertyUtils.getReadablePropertyNamesByType(element,
            LifecycleElement.class);
    Set<String> nestedElementCollectionProperties = ObjectPropertyUtils
            .getReadablePropertyNamesByCollectionType(element, LifecycleElement.class);
    if (nestedElementProperties.isEmpty() && nestedElementCollectionProperties.isEmpty()) {
        return Collections.emptyMap();
    }

    Set<String> restrictedPropertyNames = getLifecycleRestrictedProperties(element, viewPhase);

    Map<String, LifecycleElement> elements = Collections.emptyMap();

    for (String propertyName : nestedElementProperties) {
        if (restrictedPropertyNames.contains(propertyName)) {
            continue;
        }

        Object propertyValue = ObjectPropertyUtils.getPropertyValue(element, propertyName);
        elements = addElementToLifecycleMap(elements, propertyName, (LifecycleElement) propertyValue);
    }

    for (String propertyName : nestedElementCollectionProperties) {
        if (restrictedPropertyNames.contains(propertyName)) {
            continue;
        }

        Object nestedElementCollection = ObjectPropertyUtils.getPropertyValue(element, propertyName);
        if (element.getClass().isArray()) {
            for (int i = 0; i < Array.getLength(nestedElementCollection); i++) {
                elements = addElementToLifecycleMap(elements, propertyName + "[" + i + "]",
                        (LifecycleElement) Array.get(nestedElementCollection, i));
            }
        } else if (nestedElementCollection instanceof List) {
            for (int i = 0; i < ((List<?>) nestedElementCollection).size(); i++) {
                elements = addElementToLifecycleMap(elements, propertyName + "[" + i + "]",
                        (LifecycleElement) ((List<?>) nestedElementCollection).get(i));
            }
        } else if (nestedElementCollection instanceof Map) {
            for (Entry<?, ?> entry : ((Map<?, ?>) nestedElementCollection).entrySet()) {
                elements = addElementToLifecycleMap(elements, propertyName + "[" + entry.getKey() + "]",
                        (LifecycleElement) entry.getValue());
            }
        }
    }

    return elements == Collections.EMPTY_MAP ? elements : Collections.unmodifiableMap(elements);
}

From source file:org.directwebremoting.dwrunit.Verify.java

/**
 * Asserts that two object arrays are equal. If they are not, an
 * {@link AssertionError} is thrown with the given message. If <code>expecteds</code> and
 *  <code>actuals</code> are <code>null</code>, they are considered equal.
 * @param message the identifying message or <code>null</code> for the {@link AssertionError}
 * @param expecteds Object array or array of arrays (multi-dimensional array) with expected values.
 * @param actuals Object array or array of arrays (multi-dimensional array) with actual values
 *//*w w w  .  ja v a  2s .c o  m*/
private void internalArrayEquals(String message, Object expecteds, Object actuals) {
    if (expecteds == actuals) {
        return;
    }

    String header = message == null ? "" : message + ": ";
    if (expecteds == null) {
        fail(header + "expected array was null");
        return;
    }

    if (actuals == null) {
        fail(header + "actual array was null");
        return;
    }

    int actualsLength = Array.getLength(actuals);
    int expectedsLength = Array.getLength(expecteds);
    if (actualsLength != expectedsLength) {
        fail(header + "array lengths differed, expected.length=" + expectedsLength + " actual.length="
                + actualsLength);
        return;
    }

    for (int i = 0; i < expectedsLength; i++) {
        Object expected = Array.get(expecteds, i);
        Object actual = Array.get(actuals, i);

        if (isArray(expected) && isArray(actual)) {
            internalArrayEquals(message, expected, actual);
        } else {
            equals(message, expected, actual);
        }
    }
}

From source file:adams.ml.Dataset.java

public void setMappingFromBaseData(String key, BaseData bd) {

    if (bd != null) {

        if (bd.isNumeric()) {
            setType(key, BaseData.Type.NUMERIC);
        } else if (bd.isDate()) {
            setType(key, BaseData.Type.DATE);
        } else if (bd.isTime()) {
            setType(key, BaseData.Type.TIME);
        } else if (bd.isArray()) {
            if (Array.getLength(bd.getData()) > 0) {
                Object ao = Array.get(bd.getData(), 0);
                if (BaseData.isNumeric(ao)) {
                    setType(key, BaseData.Type.NUMERIC, Array.getLength(bd.getData()));
                } else {
                    setType(key, BaseData.Type.STRING, Array.getLength(bd.getData()));
                }/*from   ww w. j  av a2  s. c om*/
            }
        } else {
            setType(key, BaseData.Type.STRING);
        }
    }
}

From source file:com.gwtjs.common.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  www  . jav a  2  s. c  om
 * @param source the (potentially primitive) array
 * @return the corresponding object array (never {@code null})
 * @throws IllegalArgumentException if the parameter is not an array
 */
@SuppressWarnings("rawtypes")
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.g3net.tool.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</code> source value will be converted to an
 * empty Object array./*from   ww w.  j av  a 2 s  .c  o  m*/
 * @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:org.apache.axis2.jaxws.marshaller.impl.alt.MethodMarshallerUtils.java

/**
 * Returns the list of PDElements that need to be marshalled onto the wire
 *
 * @param marshalDesc/* w  ww  .j  av a 2 s  .  com*/
 * @param params          ParameterDescription for this operation
 * @param sigArguments    arguments
 * @param isInput         indicates if input or output  params(input args on client, 
 *                        output args on server)
 * @param isDocLitWrapped
 * @param isRPC
 * @return PDElements
 */
static List<PDElement> getPDElements(MarshalServiceRuntimeDescription marshalDesc,
        ParameterDescription[] params, Object[] sigArguments, boolean isInput, boolean isDocLitWrapped,
        boolean isRPC) {
    List<PDElement> pdeList = new ArrayList<PDElement>();

    int index = 0;
    for (int i = 0; i < params.length; i++) {
        ParameterDescription pd = params[i];

        if (pd.getMode() == Mode.IN && isInput || pd.getMode() == Mode.INOUT
                || pd.getMode() == Mode.OUT && !isInput) {

            // Get the matching signature argument
            Object value = sigArguments[i];

            // Don't consider async handlers, they are are not represented on the wire,
            // thus they don't have a PDElement
            if (isAsyncHandler(value)) {
                continue;
            }

            // Convert from Holder into value
            if (isHolder(value)) {
                value = ((Holder) value).value;
            }

            // Get the formal type representing the value
            Class formalType = pd.getParameterActualType();

            // The namespace and local name are obtained differently depending on 
            // the style/use and header
            QName qName = null;
            if (pd.isHeader()) {
                // Headers (even rpc) are marshalled with the name defined by the 
                // element= attribute on the wsd:part
                qName = new QName(pd.getTargetNamespace(), pd.getParameterName());
            } else if (isDocLitWrapped) {
                // For doc/lit wrapped, the localName comes from the PartName
                qName = new QName(pd.getTargetNamespace(), pd.getPartName());
            } else if (isRPC) {
                // Per WSI-BP, the namespace uri is unqualified
                qName = new QName(pd.getPartName());
            } else {
                qName = new QName(pd.getTargetNamespace(), pd.getParameterName());
            }

            // Create an Element rendering
            Element element = null;
            AttachmentDescription attachmentDesc = pd.getAttachmentDescription();
            if (attachmentDesc != null) {
                PDElement pde = createPDElementForAttachment(pd, qName, value, formalType);
                pdeList.add(pde);
            } else {
                if (!marshalDesc.getAnnotationDesc(formalType).hasXmlRootElement()) {
                    /* when a schema defines a SimpleType with xsd list jaxws tooling 
                     * generates artifacts with array rather than a java.util.List
                     * However the ObjectFactory definition uses a List and thus 
                     * marshalling fails. Lets convert the Arrays to List and recreate
                     * the JAXBElements for the same.
                     */
                    if (pd.isListType()) {

                        List<Object> list = new ArrayList<Object>();
                        if (formalType.isArray()) {
                            for (int count = 0; count < Array.getLength(value); count++) {
                                Object obj = Array.get(value, count);
                                list.add(obj);
                            }

                        }
                        element = new Element(list, qName, List.class);
                    } else {
                        element = new Element(value, qName, formalType);
                    }
                } else {
                    element = new Element(value, qName);
                }
                // The object is now ready for marshalling
                PDElement pde = new PDElement(pd, element, null);
                pdeList.add(pde);
            }
        }
    }

    return pdeList;
}

From source file:org.cloudata.core.common.io.CObjectWritable.java

private static void writeColumnValue(DataOutput out, Object instance, Class declaredClass, CloudataConf conf,
        int length) throws IOException {
    int shortByteSize = CWritableUtils.getShortByteSize();
    int intByteSize = CWritableUtils.getIntByteSize();

    int totalByteSize = 0;

    long startTime = System.currentTimeMillis();
    for (int i = 0; i < length; i++) {
        ColumnValue columnValue = (ColumnValue) Array.get(instance, i);
        totalByteSize += shortByteSize;//from   www.j ava  2s .  c om
        totalByteSize += columnValue.size();
    }
    //    long endTime = System.currentTimeMillis();
    //LOG.fatal("writeColumnValue1:length=" + length + ",bytes=" + totalByteSize + ",time=" + (endTime - startTime));

    out.writeInt(totalByteSize);

    //    startTime = System.currentTimeMillis();
    for (int i = 0; i < length; i++) {
        writeObject(out, Array.get(instance, i), declaredClass.getComponentType(), conf, true);
    }
    long endTime = System.currentTimeMillis();
    //LOG.fatal("writeColumnValue2:time=" + (endTime - startTime));
}

From source file:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Returns the index'th element of the supplied collection.
 * @param collection to read//  ww  w  . j  av a 2  s  . c  om
 * @param index int
 * @return collection[index]
 */
public static Object getValue(Object collection, int index) {
    collection = getValue(collection);
    Object value = collection;
    if (collection != null) {
        if (collection.getClass().isArray()) {
            if (index < 0 || index >= Array.getLength(collection)) {
                return null;
            }
            value = Array.get(collection, index);
        } else if (collection instanceof List) {
            if (index < 0 || index >= ((List) collection).size()) {
                return null;
            }
            value = ((List) collection).get(index);
        } else if (collection instanceof Collection) {
            int i = 0;
            Iterator it = ((Collection) collection).iterator();
            for (; i < index; i++) {
                it.next();
            }
            if (it.hasNext()) {
                value = it.next();
            } else {
                value = null;
            }
        }
    }
    return value;
}

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

/**
 * /*from www . ja v a 2s  . c  o  m*/
 * PriorRenderMethod 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 indexes
 * @return
 * @throws Exception
 */
default Renderer renderValueOfFields(String renderTargetStep, Object form, int[] indexes) throws Exception {
    Renderer render = Renderer.create();
    List<AnnotatedPropertyInfo> fieldList = BasicFormFlowTraitHelper.retrieveRenderTargetFieldList(form);

    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++) {
                    int[] newIndex = indexes.clone();

                    // retrieve the form instance
                    if (i >= 0) {
                        newIndex = ArrayUtils.add(newIndex, i);
                        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(rewriteCascadeFormFieldArrayRef(renderTargetStep, subForm, newIndex));
                    }

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

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

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

                if (StringUtils.isNotEmpty(containerSelector)) {
                    render.add(containerSelector, renderForm(renderTargetStep, v, indexes));
                } else {
                    render.add(renderForm(renderTargetStep, v, indexes));
                }
            }
            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());
            }
        }

        BasicFormFlowTraitHelper.FieldRenderingInfo renderingInfo = BasicFormFlowTraitHelper
                .getRenderingInfo(this, field, indexes);

        // 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.janusgraph.diskstorage.configuration.ConfigOption.java

public static final <O> Predicate<O> disallowEmpty(Class<O> clazz) {
    return new Predicate<O>() {
        @Override/*  w ww  .  j a  v a2  s .  co m*/
        public boolean apply(@Nullable O o) {
            if (o == null)
                return false;
            if (o instanceof String)
                return StringUtils.isNotBlank((String) o);
            if (o.getClass().isArray() && (Array.getLength(o) == 0 || Array.get(o, 0) == null))
                return false;
            if (o instanceof Collection
                    && (((Collection) o).isEmpty() || ((Collection) o).iterator().next() == null))
                return false;
            return true;
        }
    };
}