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.january.dataset.AbstractDataset.java

/**
 * Fill dataset from object at depth dimension
 * @param obj/*from  ww w  .j a va  2 s . co  m*/
 * @param depth
 * @param pos position
 */
protected void fillData(Object obj, final int depth, final int[] pos) {
    if (obj == null) {
        int dtype = getDType();
        if (dtype == FLOAT32)
            set(Float.NaN, pos);
        else if (dtype == FLOAT64)
            set(Double.NaN, pos);
        return;
    }

    Class<?> clazz = obj.getClass();
    if (obj instanceof List<?>) {
        List<?> jl = (List<?>) obj;
        int l = jl.size();
        for (int i = 0; i < l; i++) {
            Object lo = jl.get(i);
            fillData(lo, depth + 1, pos);
            pos[depth]++;
        }
        pos[depth] = 0;
    } else if (clazz.isArray()) {
        int l = Array.getLength(obj);
        if (clazz.equals(odata.getClass())) {
            System.arraycopy(obj, 0, odata, get1DIndex(pos), l);
        } else if (clazz.getComponentType().isPrimitive()) {
            for (int i = 0; i < l; i++) {
                set(Array.get(obj, i), pos);
                pos[depth]++;
            }
            pos[depth] = 0;
        } else {
            for (int i = 0; i < l; i++) {
                fillData(Array.get(obj, i), depth + 1, pos);
                pos[depth]++;
            }
            pos[depth] = 0;
        }
    } else if (obj instanceof IDataset) {
        boolean[] a = new boolean[shape.length];
        for (int i = depth; i < a.length; i++)
            a[i] = true;
        setSlice(obj, getSliceIteratorFromAxes(pos, a));
    } else {
        set(obj, pos);
    }
}

From source file:com.segment.analytics.internal.Utils.java

/**
 * Wraps the given object if necessary. {@link JSONObject#wrap(Object)} is only available on API
 * 19+, so we've copied the implementation. Deviates from the original implementation in
 * that it always returns {@link JSONObject#NULL} instead of {@code null} in case of a failure,
 * and returns the {@link Object#toString} of any object that is of a custom (non-primitive or
 * non-collection/map) type./*from  w  ww . j  a  v  a 2 s .  co  m*/
 *
 * <p>If the object is null or , returns {@link JSONObject#NULL}.
 * If the object is a {@link JSONArray} or {@link JSONObject}, no wrapping is necessary.
 * If the object is {@link JSONObject#NULL}, no wrapping is necessary.
 * If the object is an array or {@link Collection}, returns an equivalent {@link JSONArray}.
 * If the object is a {@link Map}, returns an equivalent {@link JSONObject}.
 * If the object is a primitive wrapper type or {@link String}, returns the object.
 * Otherwise returns the result of {@link Object#toString}.
 * If wrapping fails, returns JSONObject.NULL.
 */
private static Object wrap(Object o) {
    if (o == null) {
        return JSONObject.NULL;
    }
    if (o instanceof JSONArray || o instanceof JSONObject) {
        return o;
    }
    if (o.equals(JSONObject.NULL)) {
        return o;
    }
    try {
        if (o instanceof Collection) {
            return new JSONArray((Collection) o);
        } else if (o.getClass().isArray()) {
            final int length = Array.getLength(o);
            JSONArray array = new JSONArray();
            for (int i = 0; i < length; ++i) {
                array.put(wrap(Array.get(array, i)));
            }
            return array;
        }
        if (o instanceof Map) {
            //noinspection unchecked
            return toJsonObject((Map) o);
        }
        if (o instanceof Boolean || o instanceof Byte || o instanceof Character || o instanceof Double
                || o instanceof Float || o instanceof Integer || o instanceof Long || o instanceof Short
                || o instanceof String) {
            return o;
        }
        // Deviate from original implementation and return the String representation of the object
        // regardless of package.
        return o.toString();
    } catch (Exception ignored) {
    }
    // Deviate from original and return JSONObject.NULL instead of null.
    return JSONObject.NULL;
}

From source file:org.apache.hadoop.jmx.JMXJsonServlet.java

private void writeObject(JsonGenerator jg, Object value) throws IOException {
    if (value == null) {
        jg.writeNull();/*from  ww  w .  j av a 2s .  c o m*/
    } else {
        Class<?> c = value.getClass();
        if (c.isArray()) {
            jg.writeStartArray();
            int len = Array.getLength(value);
            for (int j = 0; j < len; j++) {
                Object item = Array.get(value, j);
                writeObject(jg, item);
            }
            jg.writeEndArray();
        } else if (value instanceof Number) {
            Number n = (Number) value;
            jg.writeNumber(n.toString());
        } else if (value instanceof Boolean) {
            Boolean b = (Boolean) value;
            jg.writeBoolean(b);
        } else if (value instanceof CompositeData) {
            CompositeData cds = (CompositeData) value;
            CompositeType comp = cds.getCompositeType();
            Set<String> keys = comp.keySet();
            jg.writeStartObject();
            for (String key : keys) {
                writeAttribute(jg, key, cds.get(key));
            }
            jg.writeEndObject();
        } else if (value instanceof TabularData) {
            TabularData tds = (TabularData) value;
            jg.writeStartArray();
            for (Object entry : tds.values()) {
                writeObject(jg, entry);
            }
            jg.writeEndArray();
        } else {
            jg.writeString(value.toString());
        }
    }
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitBareMethodMarshaller.java

public Message marshalResponse(Object returnObject, Object[] signatureArgs, OperationDescription operationDesc,
        Protocol protocol) throws WebServiceException {

    EndpointInterfaceDescription ed = operationDesc.getEndpointInterfaceDescription();
    EndpointDescription endpointDesc = ed.getEndpointDescription();

    // We want to respond with the same protocol as the request,
    // It the protocol is null, then use the Protocol defined by the binding
    if (protocol == null) {
        protocol = Protocol.getProtocolForBinding(endpointDesc.getBindingType());
    }//from w  w w.ja va 2  s.  c om

    // Note all exceptions are caught and rethrown with a WebServiceException
    try {
        // Sample Document message
        // ..
        // <soapenv:body>
        //    <m:return ... >...</m:param>
        // </soapenv:body>
        //
        // Important points.
        //   1) There is no operation element in the message
        //   2) The data blocks are located underneath the operation element. 
        //   3) The name of the data blocks (m:param) are defined by the schema.
        //      (SOAP indicates that the name of the element is not important, but
        //      for document processing, we will assume that the name corresponds to 
        //      a schema root element)
        //   4) The type of the data block is defined by schema; thus in most cases
        //      an xsi:type will not be present

        // Get the operation information
        ParameterDescription[] pds = operationDesc.getParameterDescriptions();
        MarshalServiceRuntimeDescription marshalDesc = MethodMarshallerUtils.getMarshalDesc(endpointDesc);
        TreeSet<String> packages = marshalDesc.getPackages();

        // Create the message 
        MessageFactory mf = (MessageFactory) FactoryRegistry.getFactory(MessageFactory.class);
        Message m = mf.create(protocol);

        // Put the return object onto the message
        Class returnType = operationDesc.getResultActualType();
        if (returnType != void.class) {
            AttachmentDescription attachmentDesc = operationDesc.getResultAttachmentDescription();
            if (attachmentDesc != null) {
                if (attachmentDesc.getAttachmentType() == AttachmentType.SWA) {
                    // Create an Attachment object with the signature value
                    Attachment attachment = new Attachment(returnObject, returnType, attachmentDesc,
                            operationDesc.getResultPartName());
                    m.addDataHandler(attachment.getDataHandler(), attachment.getContentID());
                    m.setDoingSWA(true);
                } else {
                    throw ExceptionFactory.makeWebServiceException(Messages.getMessage("pdElementErr"));
                }
            } else {
                Element returnElement = null;
                QName returnQName = new QName(operationDesc.getResultTargetNamespace(),
                        operationDesc.getResultName());
                if (marshalDesc.getAnnotationDesc(returnType).hasXmlRootElement()) {
                    returnElement = new Element(returnObject, returnQName);
                } else {
                    /* when a schema defines a SimpleType with xsd list jaxws tooling generates art-effects 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.
                     */
                    if (operationDesc.isListType()) {
                        List list = new ArrayList();
                        if (returnType.isArray()) {
                            for (int count = 0; count < Array.getLength(returnObject); count++) {
                                Object obj = Array.get(returnObject, count);
                                list.add(obj);
                            }
                            returnElement = new Element(list, returnQName, List.class);
                        }
                    } else {
                        returnElement = new Element(returnObject, returnQName, returnType);
                    }
                }
                MethodMarshallerUtils.toMessage(returnElement, returnType, operationDesc.isListType(),
                        marshalDesc, m, null, // always marshal using "by element" mode
                        operationDesc.isResultHeader());
            }
        }

        // Convert the holder objects into a list of JAXB objects for marshalling
        List<PDElement> pvList = MethodMarshallerUtils.getPDElements(marshalDesc, pds, signatureArgs, false, // output
                false, false);

        // Put values onto the message
        MethodMarshallerUtils.toMessage(pvList, m, packages, null);

        // Enable SWA for nested SwaRef attachments
        if (operationDesc.hasResponseSwaRefAttachments()) {
            m.setDoingSWA(true);
        }

        return m;
    } catch (Exception e) {
        throw ExceptionFactory.makeWebServiceException(e);
    }
}

From source file:org.jbpm.formModeler.core.processing.fieldHandlers.CreateDynamicObjectFieldFormatter.java

protected void renderExistingItemsTable(Form parentForm, String currentNamespace, Field field, Object value) {
    Boolean displayPage = Boolean.valueOf((String) getParameter(PARAM_DISPLAYPAGE));
    CreateDynamicObjectFieldHandler fieldHandler = (CreateDynamicObjectFieldHandler) getFieldHandlersManager()
            .getHandler(field.getFieldType());

    Form form;/*from  w w  w  .j  a v  a 2s . com*/

    form = fieldHandler.calculateFieldForm(field, field.getTableSubform(), currentNamespace);

    if (value != null) { //If it is an array, convert it to a List.
        if (value.getClass().isArray()) {
            List l = new ArrayList();
            for (int i = 0; i < Array.getLength(value); i++) {
                l.add(Array.get(value, i));
            }
            value = l;
        }
    }

    List values = (List) value;
    if (values != null && !values.isEmpty()) {
        setAttribute("className", "skn-table_border");
        setAttribute("uid", fieldUID);
        renderFragment("tableStart");
        boolean modificable = !isReadonly && Boolean.TRUE.equals(field.getUpdateItems());
        boolean deleteable = !isReadonly && Boolean.TRUE.equals(field.getDeleteItems());
        boolean visualizable = Boolean.TRUE.equals(field.getVisualizeItem());

        int colspan = 0;
        if (modificable)
            colspan++;
        if (deleteable)
            colspan++;
        if (visualizable)
            colspan++;

        setAttribute("colspan", colspan);
        renderFragment("headerStart");
        Set<Field> formFields = form.getFormFields();
        List<Field> sortedFields = new ArrayList(formFields);
        Collections.sort(sortedFields, new Field.Comparator());
        for (Field formField : sortedFields) {
            String colLabel = StringEscapeUtils.escapeHtml4(fieldI18nResourceObtainer.getFieldLabel(formField));
            setAttribute("colLabel", StringUtils.defaultString(colLabel, formField.getFieldName()));
            String colName = formField.getFieldName();
            setAttribute("colName", colName);
            renderFragment("outputColumnName");
        }
        renderFragment("headerEnd");

        try {
            for (int i = 0; i < values.size(); i++) {
                setAttribute("index", i);
                setAttribute("deleteable", deleteable);
                setAttribute("modificable", modificable);
                setAttribute("visualizable", visualizable);
                setAttribute("uid", fieldUID);
                setAttribute("parentFormId", parentForm.getId());
                setAttribute("parentNamespace", currentNamespace);
                setAttribute("field", field.getFieldName());
                setAttribute("namespace", fieldNS);
                renderFragment("outputSubformActions");

                Object o = values.get(i);
                setAttribute("formValues", o);
                setAttribute("form", form);

                String rowNamespace = fieldNS + FormProcessor.CUSTOM_NAMESPACE_SEPARATOR + i;

                getFormProcessor().read(form, rowNamespace, (Map) o);

                setAttribute("namespace", rowNamespace);

                if (Boolean.TRUE.equals(field.getEnableTableEnterData()))
                    setAttribute("renderMode", renderMode);
                else
                    setAttribute("renderMode", Form.RENDER_MODE_DISPLAY);
                if (isReadonly)
                    setAttribute("readonly", isReadonly);
                setAttribute("labelMode", Form.LABEL_MODE_HIDDEN);
                renderFragment("tableRow");

            }
        } catch (Exception e) {
            log.error("Error: ", e);
        }
        renderFragment("tableEnd");
    }
}

From source file:com.alta189.cyborg.api.util.config.ini.IniConfiguration.java

/**
 * Returns the String representation of a configuration value for writing to the file
 * @param value/*from w  w w  .  j  a  v a  2 s  . co m*/
 * @return
 */
public String toStringValue(Object value) {
    if (value == null) {
        return "null";
    }
    if (value.getClass().isArray()) {
        List<Object> toList = new ArrayList<Object>();
        final int length = Array.getLength(value);
        for (int i = 0; i < length; ++i) {
            toList.add(Array.get(value, i));
        }
        value = toList;
    }
    if (value instanceof Collection) {
        StringBuilder builder = new StringBuilder();
        for (Object obj : (Collection<?>) value) {
            if (builder.length() > 0) {
                builder.append(", ");
            }
            builder.append(obj.toString());
        }
        return builder.toString();
    } else {
        String strValue = value.toString();
        if (strValue.contains(",")) {
            strValue = '"' + strValue + '"';
        }
        return strValue;
    }
}

From source file:com.gh.bmd.jrt.android.v4.core.LoaderInvocation.java

private static int recursiveHashCode(@Nullable final Object object) {

    if (object == null) {

        return 0;
    }/*from   w  ww  .j a  v a2 s.  c o m*/

    if (object.getClass().isArray()) {

        int hashCode = 0;
        final int length = Array.getLength(object);

        for (int i = 0; i < length; i++) {

            hashCode = 31 * hashCode + recursiveHashCode(Array.get(object, i));
        }

        return hashCode;
    }

    return object.hashCode();
}

From source file:org.jgentleframework.core.interceptor.AnnotationAroundAdviceMethodInterceptor.java

/**
 * Equals./*from ww  w .  j  a  va  2 s  .  c o  m*/
 * 
 * @param o
 *            the o
 * @param proxy
 *            the proxy
 * @return true, if successful
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 */
protected boolean equals(Object o, Object proxy)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    if (!ReflectUtils.isCast(o, this.targetClass))
        return false;
    Method[] lst = this.targetClass.getDeclaredMethods();
    for (Method method : lst) {
        Object oResult;
        Object thisResult;
        method.setAccessible(true);
        oResult = method.invoke(o);
        thisResult = (Object) this.attributesMapping.get(method);
        if (thisResult == null)
            thisResult = method.getDefaultValue();
        Class<?> returnType = method.getReturnType();
        if (returnType.isArray()) {
            Object[] oResultArray = new Object[Array.getLength(oResult)];
            for (int i = 0; i < oResultArray.length; i++) {
                oResultArray[i] = Array.get(oResult, i);
            }
            Object[] thisResultArray = new Object[Array.getLength(thisResult)];
            for (int i = 0; i < thisResultArray.length; i++) {
                thisResultArray[i] = Array.get(thisResult, i);
            }
            if (oResultArray.length != thisResultArray.length)
                return false;
            if (!Arrays.equals(oResultArray, thisResultArray))
                return false;
        } else if (!oResult.equals(thisResult)) {
            return false;
        }
    }
    return true;
}

From source file:org.apache.felix.webconsole.WebConsoleUtil.java

/**
 * This method will stringify a Java object. It is mostly used to print the values
 * of unknown properties. This method will correctly handle if the passed object
 * is array and will property display it.
 *
 * If the value is byte[] the elements are shown as Hex
 *
 * @param value the value to convert// w w  w.  j  a  va  2  s  .c  om
 * @return the string representation of the value
 */
public static final String toString(Object value) {
    if (value == null) {
        return "n/a"; //$NON-NLS-1$
    } else if (value.getClass().isArray()) {
        final StringBuffer sb = new StringBuffer();
        final int len = Array.getLength(value);
        synchronized (sb) { // it's faster to synchronize ALL loop calls
            sb.append('[');
            for (int i = 0; i < len; i++) {
                final Object element = Array.get(value, i);
                if (element instanceof Byte) {
                    // convert byte[] to hex string
                    sb.append("0x"); //$NON-NLS-1$
                    final String x = Integer.toHexString(((Byte) element).intValue() & 0xff);
                    if (1 == x.length()) {
                        sb.append('0');
                    }
                    sb.append(x);
                } else {
                    sb.append(toString(element));
                }

                if (i < len - 1) {
                    sb.append(", "); //$NON-NLS-1$
                }
            }
            return sb.append(']').toString();
        }
    } else {
        return value.toString();
    }

}

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

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

    if (b instanceof Number) {
        result = new float[itemSize];
        float val = ((Number) b).floatValue();
        for (int i = 0; i < itemSize; i++)
            result[i] = val;
    } else if (b instanceof float[]) {
        result = (float[]) b;
        if (result.length < itemSize) {
            result = new float[itemSize];
            int ilen = result.length;
            for (int i = 0; i < ilen; i++)
                result[i] = ((float[]) b)[i];
        }//from   w  ww .ja v  a  2 s.com
    } else if (b instanceof List<?>) {
        result = new float[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] = (float) toReal(jl.get(i));
        }
    } else if (b.getClass().isArray()) {
        result = new float[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] = ((Number) Array.get(b, i)).floatValue();
    } 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 float[] { (float) cb.getReal() };
            break;
        case 2:
            result = new float[] { (float) cb.getReal(), (float) 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 toFloatArray(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 toFloatArray(db.getObject(new int[db.getRank()]), itemSize);
    }

    return result;
}