Example usage for java.lang.reflect Array getLength

List of usage examples for java.lang.reflect Array getLength

Introduction

In this page you can find the example usage for java.lang.reflect Array getLength.

Prototype

@HotSpotIntrinsicCandidate
public static native int getLength(Object array) throws IllegalArgumentException;

Source Link

Document

Returns the length of the specified array object, as an int .

Usage

From source file:org.apache.openjpa.kernel.AttachStrategy.java

/**
 * Attach the given field into the given instance.
 *
 * @param toAttach the detached persistent instance
 * @param sm state manager for the managed instance we're copying
 * into; <code>toAttach</code> also uses this state manager
 * @param fmd metadata on the field we're copying
 * @param nullLoaded if false, nulls will be considered unloaded and will
 * not be attached//from   w  w w  .  ja va 2 s . c om
 */
protected boolean attachField(AttachManager manager, Object toAttach, StateManagerImpl sm, FieldMetaData fmd,
        boolean nullLoaded) {
    if (fmd.isVersion() || fmd.getManagement() != FieldMetaData.MANAGE_PERSISTENT)
        return false;

    PersistenceCapable into = sm.getPersistenceCapable();
    int i = fmd.getIndex();
    provideField(toAttach, sm, i);

    int set = StateManager.SET_ATTACH;
    Object val;
    switch (fmd.getDeclaredTypeCode()) {
    case JavaTypes.BOOLEAN:
        sm.settingBooleanField(into, i, sm.fetchBooleanField(i), fetchBooleanField(i), set);
        break;
    case JavaTypes.BYTE:
        sm.settingByteField(into, i, sm.fetchByteField(i), fetchByteField(i), set);
        break;
    case JavaTypes.CHAR:
        sm.settingCharField(into, i, sm.fetchCharField(i), fetchCharField(i), set);
        break;
    case JavaTypes.DOUBLE:
        sm.settingDoubleField(into, i, sm.fetchDoubleField(i), fetchDoubleField(i), set);
        break;
    case JavaTypes.FLOAT:
        sm.settingFloatField(into, i, sm.fetchFloatField(i), fetchFloatField(i), set);
        break;
    case JavaTypes.INT:
        sm.settingIntField(into, i, sm.fetchIntField(i), fetchIntField(i), set);
        break;
    case JavaTypes.LONG:
        sm.settingLongField(into, i, sm.fetchLongField(i), fetchLongField(i), set);
        break;
    case JavaTypes.SHORT:
        sm.settingShortField(into, i, sm.fetchShortField(i), fetchShortField(i), set);
        break;
    case JavaTypes.STRING:
        String sval = fetchStringField(i);
        if (sval == null && !nullLoaded)
            return false;
        sm.settingStringField(into, i, sm.fetchStringField(i), sval, set);
        break;
    case JavaTypes.DATE:
    case JavaTypes.CALENDAR:
    case JavaTypes.NUMBER:
    case JavaTypes.BOOLEAN_OBJ:
    case JavaTypes.BYTE_OBJ:
    case JavaTypes.CHAR_OBJ:
    case JavaTypes.DOUBLE_OBJ:
    case JavaTypes.FLOAT_OBJ:
    case JavaTypes.INT_OBJ:
    case JavaTypes.LONG_OBJ:
    case JavaTypes.SHORT_OBJ:
    case JavaTypes.BIGDECIMAL:
    case JavaTypes.BIGINTEGER:
    case JavaTypes.LOCALE:
    case JavaTypes.OBJECT:
    case JavaTypes.OID:
    case JavaTypes.ENUM:
        val = fetchObjectField(i);
        if (val == null && !nullLoaded)
            return false;
        sm.settingObjectField(into, i, sm.fetchObjectField(i), val, set);
        break;
    case JavaTypes.PC:
    case JavaTypes.PC_UNTYPED:
        Object frmpc = fetchObjectField(i);
        if (frmpc == null && !nullLoaded)
            return false;

        OpenJPAStateManager tosm = manager.getBroker().getStateManager(sm.fetchObjectField(i));
        PersistenceCapable topc = (tosm == null) ? null : tosm.getPersistenceCapable();
        if (frmpc != null || topc != null) {
            if (fmd.getCascadeAttach() == ValueMetaData.CASCADE_NONE) {
                // Use the attached copy of the object, if available
                PersistenceCapable cpy = manager.getAttachedCopy(frmpc);
                if (cpy != null) {
                    frmpc = cpy;
                } else {
                    frmpc = getReference(manager, frmpc, sm, fmd);
                }
            } else {
                PersistenceCapable intopc = topc;
                if (!fmd.isEmbeddedPC() && frmpc != null && topc != null
                        && !ObjectUtils.equals(topc.pcFetchObjectId(), manager.getDetachedObjectId(frmpc))) {
                    intopc = null;
                }
                frmpc = manager.attach(frmpc, intopc, sm, fmd, false);
            }
            if (frmpc != topc)
                sm.settingObjectField(into, i, topc, frmpc, set);
        }
        break;
    case JavaTypes.COLLECTION:
        Collection frmc = (Collection) fetchObjectField(i);
        if (frmc == null && !nullLoaded)
            return false;
        Collection toc = (Collection) sm.fetchObjectField(i);
        if ((toc != null && !toc.isEmpty()) || frmc != null && !frmc.isEmpty()) {
            if (frmc == null)
                sm.settingObjectField(into, i, toc, null, set);
            else if (toc == null) {
                sm.settingObjectField(into, i, null, attachCollection(manager, frmc, sm, fmd), set);
            } else if (toc instanceof Set && frmc instanceof Set)
                replaceCollection(manager, frmc, toc, sm, fmd);
            else {
                sm.settingObjectField(into, i, toc, replaceList(manager, frmc, toc, sm, fmd), set);
            }
        }
        break;
    case JavaTypes.MAP:
        Map frmm = (Map) fetchObjectField(i);
        if (frmm == null && !nullLoaded)
            return false;
        Map tom = (Map) sm.fetchObjectField(i);
        if ((tom != null && !tom.isEmpty()) || (frmm != null && !frmm.isEmpty())) {
            if (frmm == null)
                sm.settingObjectField(into, i, tom, null, set);
            else if (tom == null)
                sm.settingObjectField(into, i, null, attachMap(manager, frmm, sm, fmd), set);
            else
                replaceMap(manager, frmm, tom, sm, fmd);
        }
        break;
    case JavaTypes.ARRAY:
        Object frma = fetchObjectField(i);
        if (frma == null && !nullLoaded)
            return false;
        Object toa = sm.fetchObjectField(i);
        if ((toa != null && Array.getLength(toa) > 0) || (frma != null && Array.getLength(frma) > 0)) {
            if (frma == null)
                sm.settingObjectField(into, i, toa, null, set);
            else
                sm.settingObjectField(into, i, toa, replaceArray(manager, frma, toa, sm, fmd), set);
        }
        break;
    default:
        throw new InternalException(fmd.toString());
    }
    return true;
}

From source file:org.archive.crawler.restlet.JobRelatedResource.java

/**
 * Constructs a nested Map data structure of the information represented
 * by {@code object}. The result is particularly suitable for use with with
 * {@link XmlMarshaller}.// ww w  .  j  a v  a  2  s  . c  om
 * 
 * @param field
 *            field name for object
 * @param object
 *            object to make presentable map for
 * @param alreadyWritten
 *            Set of objects already made presentable whose addition to the
 *            Map should be suppressed
 * @param beanPathPrefix
 *            beanPath prefix to apply to sub fields browse links
 * @return the presentable Map
 */
protected Map<String, Object> makePresentableMapFor(String field, Object object, HashSet<Object> alreadyWritten,
        String beanPathPrefix) {
    Map<String, Object> info = new LinkedHashMap<String, Object>();
    Reference baseRef = getRequest().getResourceRef().getBaseRef();

    String beanPath = beanPathPrefix;

    if (StringUtils.isNotBlank(field)) {
        info.put("field", field);

        if (StringUtils.isNotBlank(beanPathPrefix)) {
            if (beanPathPrefix.endsWith(".")) {
                beanPath += field;
            } else if (beanPathPrefix.endsWith("[")) {
                beanPath += field + "]";
            }
            info.put("url", new Reference(baseRef, "../beans/" + TextUtils.urlEscape(beanPath)).getTargetRef());
        }
    }
    String key = getBeanToNameMap().get(object);

    if (object == null) {
        info.put("propValue", null);
        return info;
    }
    if (object instanceof String || BeanUtils.isSimpleValueType(object.getClass()) || object instanceof File) {
        info.put("class", object.getClass().getName());
        info.put("propValue", object);
        return info;
    }
    if (alreadyWritten.contains(object)) {
        info.put("propValuePreviouslyDescribed", true);
        return info;
    }

    alreadyWritten.add(object); // guard against repeats and cycles

    if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(field)) {
        info.put("key", key);
        info.put("url", new Reference(baseRef, "../beans/" + key).getTargetRef());
        return info;
    }

    info.put("class", object.getClass().getName());

    Collection<Object> properties = new LinkedList<Object>();
    BeanWrapperImpl bwrap = new BeanWrapperImpl(object);
    for (PropertyDescriptor pd : getPropertyDescriptors(bwrap)) {

        if (pd.getReadMethod() != null && !pd.isHidden()) {
            String propName = pd.getName();
            if (beanPath != null) {
                beanPathPrefix = beanPath + ".";
            }
            Object propValue = makePresentableMapFor(propName, bwrap.getPropertyValue(propName), alreadyWritten,
                    beanPathPrefix);
            properties.add(propValue);
        }
    }
    if (properties.size() > 0) {
        info.put("properties", properties);
    }

    Collection<Object> propValues = new LinkedList<Object>();
    if (object.getClass().isArray()) {
        // TODO: may want a special handling for an array of
        // primitive types?
        int len = Array.getLength(object);
        for (int i = 0; i < len; i++) {
            if (beanPath != null) {
                beanPathPrefix = beanPath + "[";
            }
            // TODO: protect against overlong content? 
            propValues.add(makePresentableMapFor(i + "", Array.get(object, i), alreadyWritten, beanPathPrefix));
        }
    }
    if (object instanceof List<?>) {
        List<?> list = (List<?>) object;
        for (int i = 0; i < list.size(); i++) {
            if (beanPath != null) {
                beanPathPrefix = beanPath + "[";
            }
            // TODO: protect against overlong content?
            try {
                propValues.add(makePresentableMapFor(i + "", list.get(i), alreadyWritten, beanPathPrefix));
            } catch (Exception e) {
                LOGGER.warning(list + ".get(" + i + ") -" + e);
            }
        }
    } else if (object instanceof Iterable<?>) {
        for (Object next : (Iterable<?>) object) {
            propValues.add(makePresentableMapFor("#", next, alreadyWritten, beanPathPrefix));
        }
    }
    if (object instanceof Map<?, ?>) {
        for (Object next : ((Map<?, ?>) object).entrySet()) {
            // TODO: protect against giant maps?
            Map.Entry<?, ?> entry = (Map.Entry<?, ?>) next;
            if (beanPath != null) {
                beanPathPrefix = beanPath + "[";
            }
            propValues.add(makePresentableMapFor(entry.getKey().toString(), entry.getValue(), alreadyWritten,
                    beanPathPrefix));
        }
    }
    if (propValues.size() > 0) {
        info.put("propValue", propValues);
    }

    return info;
}

From source file:edu.ucla.stat.SOCR.analyses.gui.Chart.java

private XYDataset createXYDataset(String lineName, double x[], double y[]) {
    XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries serie = new XYSeries(lineName);
    for (int i = 0; i < Array.getLength(x); i++)
        serie.add(x[i], y[i]);/* w  w  w.jav a  2 s  .c o m*/

    dataset.addSeries(serie);

    return dataset;
}

From source file:com.wavemaker.json.JSONMarshaller.java

/**
 * doMarshal() returns some status Objects.
 * //from ww  w  . j ava  2 s. c  o m
 * CYCLE_DETECTED_OBJECT will be returned if a cycle was detected at a lower level, and this level needs to be not
 * written.
 * 
 * fieldDefinition should never be null; its enclosed typeDefinition may very well be null.
 */
protected static Object doMarshal(Writer writer, Object obj, Object root, JSONState js, boolean sort,
        boolean topLevel, Stack<Object> touchedObjects, Stack<String> propertyNames,
        FieldDefinition fieldDefinition, int arrayLevel, TypeState typeState, boolean prettyPrint, int level,
        Logger logger) throws IOException {

    if (fieldDefinition == null) {
        throw new NullArgumentException("fieldDefinition");
    }

    touchedObjects.push(obj);
    try {
        if (obj != null && fieldDefinition.getTypeDefinition() == null) {
            fieldDefinition = ReflectTypeUtils.getFieldDefinition(obj.getClass(), typeState, false, null);
            arrayLevel = 0;
        }

        // do value conversion
        if (js.getValueTransformer() != null) {
            Tuple.Three<Object, FieldDefinition, Integer> tuple = js.getValueTransformer().transformToJSON(obj,
                    fieldDefinition, arrayLevel, root, getPropertyName(propertyNames, js), js.getTypeState());
            if (tuple != null) {
                obj = tuple.v1;
                fieldDefinition = tuple.v2;
                arrayLevel = tuple.v3;
            }
        }

        if (arrayLevel == fieldDefinition.getDimensions() && fieldDefinition.getTypeDefinition() != null
                && fieldDefinition.getTypeDefinition() instanceof WriteObjectConverter) {
            ((WriteObjectConverter) fieldDefinition.getTypeDefinition()).writeObject(obj, root,
                    getPropertyName(propertyNames, js), writer);
        } else if (obj == null) {
            writer.write("null");

            // handle arrays & Collections
        } else if (arrayLevel < fieldDefinition.getDimensions() || obj.getClass().isArray()) {

            writer.write("[");
            boolean firstElement = true;

            if (obj instanceof Collection) {
                for (Object elem : (Collection<?>) obj) {
                    if (!firstElement) {
                        writer.write(",");

                        if (prettyPrint) {
                            writer.write(" ");
                        }
                    }

                    doMarshal(writer, elem, root, js, sort, false, touchedObjects, propertyNames,
                            fieldDefinition, arrayLevel + 1, typeState, prettyPrint, level, logger);

                    if (firstElement) {
                        firstElement = false;
                    }
                }
            } else if (obj.getClass().isArray()) {
                int length = Array.getLength(obj);
                Object elem;

                for (int i = 0; i < length; i++) {
                    elem = Array.get(obj, i);

                    if (!firstElement) {
                        writer.write(",");

                        if (prettyPrint) {
                            writer.write(" ");
                        }
                    }

                    doMarshal(writer, elem, root, js, sort, false, touchedObjects, propertyNames,
                            fieldDefinition, arrayLevel + 1, typeState, prettyPrint, level, logger);
                    if (firstElement) {
                        firstElement = false;
                    }
                }
            } else {
                throw new WMRuntimeException(MessageResource.JSON_UNKNOWN_COLL_OR_ARRAY, obj, obj.getClass());
            }

            writer.write("]");
            // check for primitives
        } else if (fieldDefinition.getTypeDefinition() != null
                && fieldDefinition.getTypeDefinition() instanceof PrimitiveTypeDefinition) {
            ((PrimitiveTypeDefinition) fieldDefinition.getTypeDefinition()).toJson(writer, obj);
            // handle maps & objects
        } else {
            handleObject(obj, root, js, writer, touchedObjects, propertyNames, sort, fieldDefinition,
                    arrayLevel, typeState, prettyPrint, level, logger);
        }

        return null;
    } finally {
        touchedObjects.pop();
    }
}

From source file:de.jgoldhammer.alfresco.jscript.jmx.JmxDumpUtil.java

/**
 * Outputs a single value, dealing with nested arrays and CompositeData
 * objects.// www. java2  s. c  om
 * 
 * @param out
 *            PrintWriter to write the output to
 * @param value
 *            the value to output
 * @param nestLevel
 *            the nesting level
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void outputValue(PrintWriter out, Object value, int nestLevel) throws IOException {
    if (value == null) {
        out.println(JmxDumpUtil.NULL_VALUE);
    } else if (value.getClass().isArray()) {
        int length = Array.getLength(value);
        if (length == 0) {
            out.println("[]");
        } else {
            out.println();
            indent(out, nestLevel + 1);
            out.println('[');
            for (int i = 0; i < length; i++) {
                indent(out, nestLevel + 2);
                outputValue(out, Array.get(value, i), nestLevel + 2);
                if (i + 1 < length) {
                    indent(out, nestLevel + 1);
                    out.println(',');
                }
            }
            indent(out, nestLevel + 1);
            out.println(']');
        }
    } else if (value instanceof CompositeData) {
        out.println();
        indent(out, nestLevel + 1);
        out.println('[');
        printCompositeInfo((CompositeData) value, out, nestLevel + 2);
        indent(out, nestLevel + 1);
        out.println(']');
    } else {
        out.println(value.toString());
    }
}

From source file:com.dnw.json.J.java

/**
 * Appends the given array to the string buffer.
 * //from   ww  w . j a va 2  s.  c  o  m
 * @author manbaum
 * @since Oct 11, 2014
 * @param sb the string buffer.
 * @param array the array to append.
 */
private final static void emitArray(final StringBuffer sb, final Object array) {
    sb.append('[');
    int length = Array.getLength(array);
    for (int i = 0; i < length; i++) {
        if (i > 0) {
            sb.append(',');
        }
        J.emit(sb, Array.get(array, i));
    }
    sb.append(']');
}

From source file:ArrayUtils.java

/**
 * Merges elements found in each of a set of arrays into a single array with
 * no duplicates. For primitive types./*w  w w . jav  a 2  s.com*/
 * 
 * @param type
 *            The type of the result
 * @param arrays
 *            The arrays to merge
 * @return A new array containing all common elements between
 *         <code>array1</code> and <code>array2</code>
 * @throws NullPointerException
 *             If either array is null
 * @throws ArrayStoreException
 *             If elements in the arrays are incompatible with
 *             <code>type</code>
 */
public static Object mergeExclusiveP(Class<?> type, Object... arrays) {
    if (arrays.length == 0)
        return Array.newInstance(type, 0);
    java.util.ArrayList<Object> retSet = new java.util.ArrayList<Object>();
    int i, j, k;
    int len = Array.getLength(arrays[0]);
    for (j = 0; j < len; j++)
        retSet.add(Array.get(arrays[0], j));
    for (i = 1; i < arrays.length; i++) {
        for (j = 0; j < retSet.size(); j++) {
            len = Array.getLength(arrays[i]);
            boolean hasEl = false;
            for (k = 0; k < len; k++)
                if (equalsUnordered(retSet.get(j), Array.get(arrays[i], k))) {
                    hasEl = true;
                    break;
                }
            if (!hasEl) {
                retSet.remove(j);
                j--;
            }
        }
    }
    Object ret = Array.newInstance(type, retSet.size());
    for (i = 0; i < retSet.size(); i++)
        Array.set(ret, i, retSet.get(i));
    return ret;
}

From source file:edu.ucla.stat.SOCR.analyses.gui.Chart.java

private XYDataset createXYDataset(int numberOfLines, String[] lineNames, double x[][], double y[][]) {
    XYSeriesCollection dataset = new XYSeriesCollection();
    for (int j = 0; j < numberOfLines; j++) {
        XYSeries serie = new XYSeries(lineNames[j]);
        int len = Array.getLength(x[j]);
        for (int i = 0; i < len; i++)
            serie.add(x[j][i], y[j][i]);

        dataset.addSeries(serie);//from  w w  w  .j av a  2s  .  c  om
    }

    return dataset;
}

From source file:org.springmodules.validation.bean.BeanValidator.java

/**
 * Validates the elements of the given array property.
 *
 * @param root The root of the object graph that is being validated.
 * @param array The given array.//from ww  w.  j  a  va 2  s. co m
 * @param propertyName The name of the array property.
 * @param errors The {@link Errors} instance where all validation errors will be registered.
 * @param validatedObjects A registry of all objects that were already validated.
 */
protected void validateArrayProperty(Object root, Object array, String propertyName, Errors errors,
        Set validatedObjects) {

    for (int i = 0; i < Array.getLength(array); i++) {
        String nestedPath = propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX;
        errors.pushNestedPath(nestedPath);
        validateObjectGraphConstraints(root, Array.get(array, i), errors, validatedObjects);
        errors.popNestedPath();
    }
}

From source file:ObjectInspector.java

/**
 * Attempts to build a nicer looking string than the basic
 * {@link Object}.toString()/*from www  . j  a v  a 2  s  . co m*/
 * 
 * @param o
 *           The object to build from
 * @return A descriptive string
 */
private static String buildString(Object o) {
    if (o == null) {
        return "null";
    }

    // first see if there is a version of toString more specific
    // than that supplied by Object...
    try {
        Method m = o.getClass().getMethod("toString");

        if (!m.getDeclaringClass().equals(Object.class)) {
            return o.toString();
        }
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    }

    // then see if it is an array...
    if (o.getClass().isArray()) {
        StringBuilder buff = new StringBuilder(" [ ");

        for (int i = 0; i < Array.getLength(o); i++) {
            /*
             * this could recurse infinitely, but only if the user is
             * trying to be malicious, like so - Object[] array = new
             * Object[ 1 ]; array[ 0 ] = array; - which, I'm sure
             * we'll agree, is and odd thing to do. I say let the
             * StackOverflowException catch it.
             */

            buff.append(buildString(Array.get(o, i)));
            buff.append(", ");
        }

        if (Array.getLength(o) > 0) {
            buff.delete(buff.length() - 2, buff.length());
        }

        buff.append(" ]");

        return buff.toString();
    }

    return getObjectPosition(o);
}