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.hadoop.hbase.io.HbaseObjectWritable.java

/**
 * Write a {@link Writable}, {@link String}, primitive type, or an array of
 * the preceding./*www .jav  a  2s .co m*/
 * @param out
 * @param instance
 * @param declaredClass
 * @param conf
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static void writeObject(DataOutput out, Object instance, Class declaredClass, Configuration conf)
        throws IOException {

    Object instanceObj = instance;
    Class declClass = declaredClass;

    if (instanceObj == null) { // null
        instanceObj = new NullInstance(declClass, conf);
        declClass = Writable.class;
    }
    writeClassCode(out, declClass);
    if (declClass.isArray()) { // array
        // If bytearray, just dump it out -- avoid the recursion and
        // byte-at-a-time we were previously doing.
        if (declClass.equals(byte[].class)) {
            Bytes.writeByteArray(out, (byte[]) instanceObj);
        } else if (declClass.equals(Result[].class)) {
            Result.writeArray(out, (Result[]) instanceObj);
        } else {
            //if it is a Generic array, write the element's type
            if (getClassCode(declaredClass) == GENERIC_ARRAY_CODE) {
                Class<?> componentType = declaredClass.getComponentType();
                writeClass(out, componentType);
            }

            int length = Array.getLength(instanceObj);
            out.writeInt(length);
            for (int i = 0; i < length; i++) {
                Object item = Array.get(instanceObj, i);
                writeObject(out, item, item.getClass(), conf);
            }
        }
    } else if (List.class.isAssignableFrom(declClass)) {
        List list = (List) instanceObj;
        int length = list.size();
        out.writeInt(length);
        for (int i = 0; i < length; i++) {
            Object elem = list.get(i);
            writeObject(out, elem, elem == null ? Writable.class : elem.getClass(), conf);
        }
    } else if (declClass == String.class) { // String
        Text.writeString(out, (String) instanceObj);
    } else if (declClass.isPrimitive()) { // primitive type
        if (declClass == Boolean.TYPE) { // boolean
            out.writeBoolean(((Boolean) instanceObj).booleanValue());
        } else if (declClass == Character.TYPE) { // char
            out.writeChar(((Character) instanceObj).charValue());
        } else if (declClass == Byte.TYPE) { // byte
            out.writeByte(((Byte) instanceObj).byteValue());
        } else if (declClass == Short.TYPE) { // short
            out.writeShort(((Short) instanceObj).shortValue());
        } else if (declClass == Integer.TYPE) { // int
            out.writeInt(((Integer) instanceObj).intValue());
        } else if (declClass == Long.TYPE) { // long
            out.writeLong(((Long) instanceObj).longValue());
        } else if (declClass == Float.TYPE) { // float
            out.writeFloat(((Float) instanceObj).floatValue());
        } else if (declClass == Double.TYPE) { // double
            out.writeDouble(((Double) instanceObj).doubleValue());
        } else if (declClass == Void.TYPE) { // void
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declClass);
        }
    } else if (declClass.isEnum()) { // enum
        Text.writeString(out, ((Enum) instanceObj).name());
    } else if (Message.class.isAssignableFrom(declaredClass)) {
        Text.writeString(out, instanceObj.getClass().getName());
        ((Message) instance).writeDelimitedTo(DataOutputOutputStream.constructOutputStream(out));
    } else if (Writable.class.isAssignableFrom(declClass)) { // Writable
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ((Writable) instanceObj).write(out);
    } else if (Serializable.class.isAssignableFrom(declClass)) {
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(instanceObj);
            byte[] value = bos.toByteArray();
            out.writeInt(value.length);
            out.write(value);
        } finally {
            if (bos != null)
                bos.close();
            if (oos != null)
                oos.close();
        }
    } else {
        throw new IOException("Can't write: " + instanceObj + " as " + declClass);
    }
}

From source file:ArrayUtils.java

/**
 * @param anArray/*from   w  w  w.ja v a  2 s  .  co m*/
 *            The array to search
 * @param anElement
 *            The element to search for
 * @return The first index <code>0&lt;=idx&lt;anArray.length</code> such
 *         that {@link #equals(Object, Object)} returns true for both
 *         <code>anArray[idx]</code> and <code>anElement</code>, or -1 if no
 *         such index exists
 */
public static int indexOfP(Object anArray, Object anElement) {
    if (anArray == null)
        return -1;
    if (anArray instanceof Object[]) {
        Object[] array2 = (Object[]) anArray;
        for (int i = 0; i < array2.length; i++) {
            if (equals(array2[i], anElement))
                return i;
        }
        return -1;
    } else {
        int i, len;
        len = Array.getLength(anArray);
        for (i = 0; i < len; i++) {
            if (equals(Array.get(anArray, i), anElement))
                return i;
        }
        return -1;
    }
}

From source file:gda.device.scannable.ScannableUtils.java

/**
 * Given a current position and an incremental move, calculates the target position.
 * <p>/*ww  w  .j  a  v  a2s  .c  om*/
 * This assumes that both objects are of the same type and are one of: number, Java array of numbers, Jython array
 * of numbers
 * 
 * @param previousPoint
 * @param step
 * @return the target position of the relative move
 */
public static Object calculateNextPoint(Object previousPoint, Object step) {

    // check we have valid values
    if (previousPoint == null) {
        return null;
    }

    if (step == null) {
        return previousPoint;
    }

    // convert both inputs to arrays of doubles
    Double[] previousArray = objectToArray(previousPoint);
    Double[] stepArray = objectToArray(step);

    // then add the arrays
    int length = Array.getLength(previousArray);
    Double[] output = addLists(length, previousArray, stepArray);

    if (output.length == 1) {
        return output[0];
    }
    // else
    return output;

}

From source file:com.roncoo.pay.permission.utils.ValidateUtils.java

/**
 * ??NULL,CollectionMap(?)//from  ww w . j  a va2  s.  co  m
 * 
 * @param obj
 *            ?
 * @param message
 *            ?
 */
@SuppressWarnings("rawtypes")
public static void checkNotEmpty(Object obj, String message) {
    if (obj == null) {
        throw new IllegalArgumentException(message);
    }
    if (obj instanceof String && obj.toString().trim().length() == 0) {
        throw new IllegalArgumentException(message);
    }
    if (obj.getClass().isArray() && Array.getLength(obj) == 0) {
        throw new IllegalArgumentException(message);
    }
    if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
        throw new IllegalArgumentException(message);
    }
    if (obj instanceof Map && ((Map) obj).isEmpty()) {
        throw new IllegalArgumentException(message);
    }
}

From source file:com.taobao.adfs.util.Utilities.java

public static String deepToString(Object object) {
    if (object == null) {
        return "null";
    } else if (object instanceof Throwable) {
        return getThrowableStackTrace((Throwable) object);
    } else if (object.getClass().isEnum()) {
        return object.toString();
    } else if (object.getClass().isArray()) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(object.getClass().getSimpleName());
        int length = Array.getLength(object);
        stringBuilder.insert(stringBuilder.length() - 1, Array.getLength(object)).append("{");
        for (int i = 0; i < length; i++) {
            stringBuilder.append(deepToString(Array.get(object, i)));
            if (i < length - 1)
                stringBuilder.append(',');
        }//w  ww . j  a  v  a2 s. c  o  m
        return stringBuilder.append("}").toString();
    } else if (List.class.isAssignableFrom(object.getClass())) {
        List<?> listObject = ((List<?>) object);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(object.getClass().getSimpleName()).append('[').append(listObject.size())
                .append(']');
        stringBuilder.append("{");
        for (Object subObject : listObject) {
            stringBuilder.append(deepToString(subObject)).append(',');
        }
        if (!listObject.isEmpty())
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        return stringBuilder.append('}').toString();
    } else {
        try {
            Method toStringMethod = Invocation.getPublicMethod(object.getClass(), "toString");
            if (toStringMethod.getDeclaringClass() == Object.class)
                return toStringByFields(object, false);
        } catch (Throwable t) {
        }
        try {
            return object.toString();
        } catch (Throwable t) {
            return "FailToString";
        }
    }
}

From source file:com.xpfriend.fixture.cast.temp.ObjectValidatorBase.java

protected boolean canValidate(Object object) {
    if (object == null) {
        return false;
    }//from  w w  w .j a va2 s . c  o m

    if (object instanceof List<?>) {
        List<?> list = (List<?>) object;
        if (list.size() == 0) {
            return false;
        }
        return isValidatableObject(list.get(0));
    }

    if (object.getClass().isArray()) {
        if (Array.getLength(object) == 0) {
            return false;
        }
        return isValidatableObject(Array.get(object, 0));
    }

    return isValidatableObject(object);
}

From source file:ArrayUtils.java

/**
 * Removes the specified object from the array. For primitive types.
 * /*from   w  w w  . j  av  a  2 s.  c  o m*/
 * @param anArray
 *            The array to remove an element from
 * @param anIndex
 *            The index of the element to remove
 * @return A new array with all the elements of <code>anArray</code> except
 *         the element at <code>anIndex</code>
 */
public static Object removeP(Object anArray, int anIndex) {
    Object ret;
    int length;
    if (anArray == null)
        return null;
    else {
        length = Array.getLength(anArray);
        ret = Array.newInstance(anArray.getClass().getComponentType(), length - 1);
    }
    System.arraycopy(anArray, 0, ret, 0, anIndex);
    System.arraycopy(anArray, anIndex + 1, ret, anIndex, length - anIndex - 1);
    return ret;
}

From source file:com.frostwire.android.LollipopFileSystem.java

private static String getVolumeId(Context context, final String volumePath) {
    try {//w w w.  ja v a 2s. co m
        StorageManager mStorageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);

        Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");

        Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
        Method getUuid = storageVolumeClazz.getMethod("getUuid");
        Method getPath = storageVolumeClazz.getMethod("getPath");
        Object result = getVolumeList.invoke(mStorageManager);

        final int length = Array.getLength(result);
        for (int i = 0; i < length; i++) {
            Object storageVolumeElement = Array.get(result, i);
            String path = (String) getPath.invoke(storageVolumeElement);

            if (path != null) {
                if (path.equals(volumePath)) {
                    return (String) getUuid.invoke(storageVolumeElement);
                }
            }
        }

        // not found.
        return null;
    } catch (Exception ex) {
        return null;
    }
}

From source file:com.roncoo.pay.permission.utils.ValidateUtils.java

/**
 * ???NULL,CollectionMap(?)/*from   w ww  .java  2s . c om*/
 * 
 * @param obj
 * @return
 */
@SuppressWarnings("rawtypes")
public static boolean isEmpty(Object obj) {
    if (obj == null) {
        return true;
    }
    if (obj instanceof String && obj.toString().trim().length() == 0) {
        return true;
    }
    if (obj.getClass().isArray() && Array.getLength(obj) == 0) {
        return true;
    }
    if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
        return true;
    }
    if (obj instanceof Map && ((Map) obj).isEmpty()) {
        return true;
    }
    return false;
}

From source file:com.flexive.faces.FxJsfComponentUtils.java

/**
 * Check if an item is selected// w  w  w .java2  s  .c  o  m
 *
 * @param context    faces context
 * @param component  our component
 * @param itemValue  the value to check for selection
 * @param valueArray all values to compare against
 * @param converter  the converter
 * @return selected
 */
public static boolean isSelectItemSelected(FacesContext context, UIComponent component, Object itemValue,
        Object valueArray, Converter converter) {
    if (itemValue == null && valueArray == null)
        return true;
    if (null != valueArray) {
        if (!valueArray.getClass().isArray()) {
            LOG.warn("valueArray is not an array, the actual type is " + valueArray.getClass());
            return valueArray.equals(itemValue);
        }
        int len = Array.getLength(valueArray);
        for (int i = 0; i < len; i++) {
            Object value = Array.get(valueArray, i);
            if (value == null && itemValue == null) {
                return true;
            } else {
                if ((value == null) ^ (itemValue == null))
                    continue;

                Object compareValue;
                if (converter == null) {
                    compareValue = coerceToModelType(context, itemValue, value.getClass());
                } else {
                    compareValue = itemValue;
                    if (compareValue instanceof String && !(value instanceof String)) {
                        // type mismatch between the time and the value we're
                        // comparing.  Invoke the Converter.
                        compareValue = converter.getAsObject(context, component, (String) compareValue);
                    }
                }

                if (value.equals(compareValue))
                    return true; //selected
            }
        }
    }
    return false;
}