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:ArrayUtils.java

/**
 * Returns a copy of the given array of size 1 greater than the argument. 
 * The last value of the array is left to the default value.
 * /*  w  w w. ja va 2s .co m*/
 * @param array The array to copy, must not be <code>null</code>.
 * @param newArrayComponentType If <code>array</code> is <code>null</code>, create a 
 * size 1 array of this type.
 * @return A new copy of the array of size 1 greater than the input.
 */
private static Object copyArrayGrow1(final Object array, final Class<?> newArrayComponentType) {
    if (array != null) {
        int arrayLength = Array.getLength(array);
        Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);
        System.arraycopy(array, 0, newArray, 0, arrayLength);
        return newArray;
    } else {
        return Array.newInstance(newArrayComponentType, 1);
    }
}

From source file:org.apache.hawq.pxf.service.BridgeOutputBuilder.java

/**
 * Fills one GPDBWritable field./*from  w w w. ja  v a  2s . co  m*/
 *
 * @param oneField field
 * @param colIdx column index
 * @throws BadRecordException if field type is not supported or doesn't
 *             match the schema
 */
void fillOneGPDBWritableField(OneField oneField, int colIdx) throws BadRecordException {
    int type = oneField.type;
    Object val = oneField.val;
    GPDBWritable gpdbOutput = (GPDBWritable) output;
    try {
        switch (DataType.get(type)) {
        case INTEGER:
            gpdbOutput.setInt(colIdx, (Integer) val);
            break;
        case FLOAT8:
            gpdbOutput.setDouble(colIdx, (Double) val);
            break;
        case REAL:
            gpdbOutput.setFloat(colIdx, (Float) val);
            break;
        case BIGINT:
            gpdbOutput.setLong(colIdx, (Long) val);
            break;
        case SMALLINT:
            gpdbOutput.setShort(colIdx, (Short) val);
            break;
        case BOOLEAN:
            gpdbOutput.setBoolean(colIdx, (Boolean) val);
            break;
        case BYTEA:
            byte[] bts = null;
            if (val != null) {
                int length = Array.getLength(val);
                bts = new byte[length];
                for (int j = 0; j < length; j++) {
                    bts[j] = Array.getByte(val, j);
                }
            }
            gpdbOutput.setBytes(colIdx, bts);
            break;
        case VARCHAR:
        case BPCHAR:
        case CHAR:
        case TEXT:
        case NUMERIC:
        case TIMESTAMP:
        case DATE:
            gpdbOutput.setString(colIdx, ObjectUtils.toString(val, null));
            break;
        default:
            String valClassName = (val != null) ? val.getClass().getSimpleName() : null;
            throw new UnsupportedOperationException(valClassName + " is not supported for HAWQ conversion");
        }
    } catch (TypeMismatchException e) {
        throw new BadRecordException(e);
    }
}

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 ww . j a va 2  s .c  o  m*/
 * @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:cat.albirar.framework.dynabean.impl.DynaBeanImpl.java

/**
 * Clone or copy a property value./*from  w ww  .  j  a va2s. c  o m*/
 * Only applicable on clone call.
 * <ul>
 * <li>If {@code originalValue} is {@link Cloneable}, makes a clone.</li>
 * <li>If {@code originalValue} IS NOT {@link Cloneable}, search for an {@link PropertyEditor editor} and copy.</li>
 * <li>If cannot found a properly {@link PropertyEditor editor}, simply return the {@code originalValue}</li>
 * </ul>
 * @param propDesc The property descriptor
 * @param originalValue The value to clone
 * @return The cloned value
 */
private Object cloneValue(DynaBeanPropertyDescriptor propDesc, Object originalValue) {
    Iterator<?> iterator;
    int n;
    IPropertyWriter writer;
    ITransformerVisitor<Object> reader;

    // only null?
    if (originalValue == null) {
        return null;
    }

    if (propDesc.isItemDynaBean()) {
        reader = new ObjectCopyReaderVisitor(descriptor.getFactory());
    } else {
        if (propDesc.getPropertyItemCloneMethod() != null) {
            reader = new ObjectCopyReaderVisitor(propDesc.getPropertyItemCloneMethod());
        } else {
            if (propDesc.getPropertyItemEditor() != null) {
                reader = new ObjectCopyReaderVisitor(propDesc.getPropertyItemEditor());
            } else {
                reader = new ObjectCopyReaderVisitor();
            }
        }
    }
    writer = prepareWriter(propDesc, reader);
    if (propDesc.isArray()) {
        for (n = 0; n < Array.getLength(originalValue); n++) {
            writer.visit(Array.get(originalValue, n));
        }
    } else {
        if (propDesc.isCollection()) {
            iterator = ((Collection<?>) originalValue).iterator();
            while (iterator.hasNext()) {
                writer.visit(iterator.next());
            }
        } else {
            writer.visit(originalValue);
        }
    }
    return writer.getReturnValue();
}

From source file:com.android.camera2.its.ItsSerializer.java

@SuppressWarnings("unchecked")
private static MetadataEntry serializeArrayEntry(Type keyType, Object keyObj, CameraMetadata md)
        throws ItsException {
    String keyName = getKeyName(keyObj);
    try {//from w w w .j a va2  s .  co m
        Object keyValue = getKeyValue(md, keyObj);
        if (keyValue == null) {
            return new MetadataEntry(keyName, JSONObject.NULL);
        }
        int arrayLen = Array.getLength(keyValue);
        Type elmtType = ((GenericArrayType) keyType).getGenericComponentType();
        if (elmtType == int.class || elmtType == float.class || elmtType == byte.class || elmtType == long.class
                || elmtType == double.class || elmtType == boolean.class) {
            return new MetadataEntry(keyName, new JSONArray(keyValue));
        } else if (elmtType == Rational.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeRational((Rational) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == Size.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeSize((Size) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == Rect.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeRect((Rect) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == Face.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeFace((Face) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == StreamConfigurationMap.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeStreamConfigurationMap((StreamConfigurationMap) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType instanceof ParameterizedType
                && ((ParameterizedType) elmtType).getRawType() == Range.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeRange((Range) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType instanceof ParameterizedType
                && ((ParameterizedType) elmtType).getRawType() == Pair.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializePair((Pair) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == MeteringRectangle.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeMeteringRectangle((MeteringRectangle) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == Location.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeLocation((Location) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == RggbChannelVector.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeRggbChannelVector((RggbChannelVector) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == BlackLevelPattern.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeBlackLevelPattern((BlackLevelPattern) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == Point.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializePoint((Point) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else {
            Logt.w(TAG, String.format("Serializing unsupported array type: " + elmtType));
            return null;
        }
    } catch (org.json.JSONException e) {
        throw new ItsException("JSON error for key: " + keyName + ": ", e);
    }
}

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

private BoxAndWhiskerCategoryDataset createBoxAndWhiskerDataset(int seriesCount, int categoryCount,
        String[] seriesName, String[][] categoryName, double[][][] values) {

    List<Double> list;

    DefaultBoxAndWhiskerCategoryDataset result = new DefaultBoxAndWhiskerCategoryDataset();

    for (int s = 0; s < seriesCount; s++) {
        for (int c = 0; c < categoryCount; c++) {
            list = new java.util.ArrayList<Double>();
            for (int i = 0; i < Array.getLength(values[s][c]); i++)
                list.add(new Double(values[s][c][i]));
            result.add(list, seriesName[s], categoryName[s][c]);
        }//  w  ww .  j  a va  2 s . co  m
    }
    return result;

}

From source file:com.googlecode.jsonplugin.JSONWriter.java

/**
 * Add array to buffer// ww w.  ja v  a  2 s . c o m
 */
private void array(Object object, Method method) throws JSONException {
    this.add("[");

    int length = Array.getLength(object);

    boolean hasData = false;
    for (int i = 0; i < length; ++i) {
        String expr = null;
        if (this.buildExpr) {
            expr = this.expandExpr(i);
            if (this.shouldExcludeProperty(expr)) {
                continue;
            }
            expr = this.setExprStack(expr);
        }
        if (hasData) {
            this.add(',');
        }
        hasData = true;
        this.value(Array.get(object, i), method);
        if (this.buildExpr) {
            this.setExprStack(expr);
        }
    }

    this.add("]");
}

From source file:ArrayUtils.java

/**
 * Concatenates a series of arrays of any type
 * //from ww  w . ja va2  s. com
 * @param type
 *            The type of the arrays
 * @param arrays
 *            The arrays to concatenate
 * @return An array containing all elements of the arrays
 */
public static Object concatP(Class<?> type, Object... arrays) {
    if (arrays.length == 0)
        return Array.newInstance(type, 0);
    if (arrays.length == 1)
        return arrays[0];
    int size = 0;
    int[] sizes = new int[arrays.length];
    for (int a = 0; a < arrays.length; a++) {
        sizes[a] = Array.getLength(arrays[a]);
        size += sizes[a];
    }
    Object ret = Array.newInstance(type, size);
    int aLen = 0;
    for (int a = 0; a < arrays.length; a++) {
        System.arraycopy(arrays[a], 0, ret, aLen, sizes[a]);
        aLen += sizes[a];
    }
    return ret;
}

From source file:ome.services.util.ServiceHandler.java

/**
 * public for testing purposes./*from   w ww.  j av  a2 s  .  c  om*/
 */
public String getResultsString(Object o, IdentityHashMap<Object, String> cache) {

    if (o == null) {
        return "null";
    }

    if (cache == null) {
        cache = new IdentityHashMap<Object, String>();
    } else {
        if (cache.containsKey(o)) {
            return (String) cache.get(o);
        }
    }

    if (o instanceof Collection) {
        int count = 0;
        StringBuilder sb = new StringBuilder(128);
        sb.append("(");
        Collection c = (Collection) o;
        for (Object obj : (c)) {
            if (count > 0) {
                sb.append(", ");
            }
            if (count > 2) {
                sb.append("... ");
                sb.append(c.size() - 3);
                sb.append(" more");
                break;
            }
            sb.append(obj);
            count++;
        }
        sb.append(")");
        return sb.toString();
    } else if (o instanceof Map) {
        Map map = (Map) o;
        int count = 0;
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (Object k : map.keySet()) {
            if (count > 0) {
                sb.append(", ");
            }
            if (count > 2) {
                sb.append("... ");
                sb.append(map.size() - 3);
                sb.append(" more");
                break;
            }
            sb.append(k);
            sb.append("=");
            cache.put(o, o.getClass().getName() + ":" + System.identityHashCode(o));
            sb.append(getResultsString(map.get(k), cache));
            count++;
        }
        sb.append("}");
        return sb.toString();
    } else if (o.getClass().isArray()) {
        int length = Array.getLength(o);
        if (length == 0) {
            return "[]";
        }
        StringBuilder sb = new StringBuilder(128);
        sb.append("[");
        for (int i = 0; i < length; i++) {

            if (i != 0) {
                sb.append(", ");
            }

            if (i > 2) {
                sb.append("... ");
                sb.append(i - 2);
                sb.append(" more");
                break;
            }
            sb.append(Array.get(o, i));
        }
        sb.append("]");
        return sb.toString();
    } else {
        return o.toString();
    }
}

From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java

public static void validIndex(int index, Object arrayOrCollection) {
    if ((!(arrayOrCollection instanceof Array)) && (!(arrayOrCollection instanceof Collection<?>))) {
        throw new IllegalArgumentException("Object is neither Array nor Collection!");
    }/*from ww  w. j  a  va2  s  . co m*/

    if (index < 0) {
        throw new IllegalArgumentException("Invalid index! Must be >= 0.");
    } else {
        int length;

        if (arrayOrCollection instanceof Array) {
            length = Array.getLength(arrayOrCollection);

            if (length < index) {
                throw new IllegalArgumentException("Invalid index! Must be < " + length);
            }
        } else if (arrayOrCollection instanceof Collection<?>) {
            Collection<?> col = (Collection<?>) arrayOrCollection;
            length = col.size();

            if (length < index) {
                throw new IllegalArgumentException("Invalid index! Must be < " + length);
            }
        } else if (arrayOrCollection instanceof Sequence<?>) {
            Sequence<?> col = (Sequence<?>) arrayOrCollection;
            length = col.getLength();

            if (length < index) {
                throw new IllegalArgumentException("Invalid index! Must be < " + length);
            }
        }
    }
}