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

/**
 * Determine if <code>obj2</code> exists in <code>obj1</code>.
 *
 * <table borer="1">/* ww w .  j a  v  a 2s .c  o m*/
 *  <tr>
 *      <td>Type Of obj1</td>
 *      <td>Comparison type</td>
 *  </tr>
 *  <tr>
 *      <td>null<td>
 *      <td>always return false</td>
 *  </tr>
 *  <tr>
 *      <td>Map</td>
 *      <td>Map containsKey(obj2)</td>
 *  </tr>
 *  <tr>
 *      <td>Collection</td>
 *      <td>Collection contains(obj2)</td>
 *  </tr>
 *  <tr>
 *      <td>Array</td>
 *      <td>there's an array element (e) where e.equals(obj2)</td>
 *  </tr>
 *  <tr>
 *      <td>Object</td>
 *      <td>obj1.equals(obj2)</td>
 *  </tr>
 * </table>
 *
 *
 * @param obj1
 * @param obj2
 * @return
 */
public static boolean contains(Object obj1, Object obj2) {
    if ((obj1 == null) || (obj2 == null)) {
        //log.debug("obj1 or obj2 are null.");
        return false;
    }

    if (obj1 instanceof Map) {
        if (((Map) obj1).containsKey(obj2)) {
            //log.debug("obj1 is a map and contains obj2");
            return true;
        }
    }
    if (obj1 instanceof Iterable) {
        Iterator iter = ((Iterable) obj1).iterator();
        while (iter.hasNext()) {
            Object value = iter.next();
            if (obj2.equals(value) || obj2.toString().equals(value)) {
                return true;
            }
        }
    } else if (obj1.getClass().isArray()) {
        for (int i = 0; i < Array.getLength(obj1); i++) {
            Object value = null;
            value = Array.get(obj1, i);

            if (obj2.equals(value)) {
                //log.debug("obj1 is an array and contains obj2");
                return true;
            }
        }
    } else if (obj1.toString().equals(obj2.toString())) {
        //log.debug("obj1 is an object and it's String representation equals obj2's String representation.");
        return true;
    } else if (obj1.equals(obj2)) {
        //log.debug("obj1 is an object and equals obj2");
        return true;
    }

    //log.debug("obj1 does not contain obj2: " + obj1 + ", " + obj2);
    return false;
}

From source file:com.nfwork.dbfound.json.converter.NumberArrayConverter.java

public Object convert(Object array) {
    if (array == null) {
        return null;
    }/*from   w  ww.  ja  v  a  2  s .co  m*/

    if (array.getClass().isArray()) {
        int length = Array.getLength(array);
        int dims = getDimensions(array.getClass());
        int[] dimensions = createDimensions(dims, length);
        Object result = Array.newInstance(type, dimensions);
        AbstractPrimitiveConverter converter = null;
        if (Byte.class.isAssignableFrom(type)) {
            converter = defaultValue != null && isUseDefault() ? new ByteConverter(defaultValue.byteValue())
                    : new ByteConverter();
        } else if (Short.class.isAssignableFrom(type)) {
            converter = defaultValue != null && isUseDefault() ? new ShortConverter(defaultValue.shortValue())
                    : new ShortConverter();
        } else if (Integer.class.isAssignableFrom(type)) {
            converter = defaultValue != null && isUseDefault() ? new IntConverter(defaultValue.intValue())
                    : new IntConverter();
        } else if (Long.class.isAssignableFrom(type)) {
            converter = defaultValue != null && isUseDefault() ? new LongConverter(defaultValue.longValue())
                    : new LongConverter();
        } else if (Float.class.isAssignableFrom(type)) {
            converter = defaultValue != null && isUseDefault() ? new FloatConverter(defaultValue.floatValue())
                    : new FloatConverter();
        } else if (Double.class.isAssignableFrom(type)) {
            converter = defaultValue != null && isUseDefault() ? new DoubleConverter(defaultValue.doubleValue())
                    : new DoubleConverter();
        }

        if (dims == 1) {
            for (int index = 0; index < length; index++) {
                try {
                    Object value = Array.get(array, index);
                    Object converted = MethodUtils.invokeMethod(converter, "convert", value);
                    Array.set(result, index, converted);
                } catch (Exception e) {
                    throw new ConversionException(e);
                }
            }
        } else {
            for (int index = 0; index < length; index++) {
                Array.set(result, index, convert(Array.get(array, index)));
            }
        }
        return result;
    } else {
        throw new ConversionException("argument is not an array: " + array.getClass());
    }
}

From source file:com.bstek.dorado.view.type.property.MappingPropertyOutputter.java

@Override
@SuppressWarnings("rawtypes")
public boolean isEscapeValue(Object value) {
    boolean shouldEscape = (value == null);
    if (!shouldEscape) {
        Mapping mapping = (Mapping) value;
        Object mapValues = mapping.getMapValues();
        shouldEscape = (mapValues == null);
        if (!shouldEscape) {
            if (mapValues instanceof Collection) {
                shouldEscape = ((Collection) mapValues).isEmpty();
            } else if (mapValues.getClass().isArray()) {
                shouldEscape = (Array.getLength(mapValues) == 0);
            }//from w ww  .j a  v  a2  s .c o m
        }
    }
    return shouldEscape;
}

From source file:Main.java

/**
 * <p>Returns the length of the specified array.
 * This method can deal with {@code Object} arrays and with primitive arrays.</p>
 *
 * <p>If the input array is {@code null}, {@code 0} is returned.</p>
 *
 * <pre>//www  .  j a v  a2s.co  m
 * ArrayUtils.getLength(null)            = 0
 * ArrayUtils.getLength([])              = 0
 * ArrayUtils.getLength([null])          = 1
 * ArrayUtils.getLength([true, false])   = 2
 * ArrayUtils.getLength([1, 2, 3])       = 3
 * ArrayUtils.getLength(["a", "b", "c"]) = 3
 * </pre>
 *
 * @param array  the array to retrieve the length from, may be null
 * @return The length of the array, or {@code 0} if the array is {@code null}
 * @throws IllegalArgumentException if the object argument is not an array.
 * @since 2.1
 */
public static int getLength(final Object array) {
    if (array == null) {
        return 0;
    }
    return Array.getLength(array);
}

From source file:Main.java

/**
 * <p>Returns the length of the specified array.
 * This method can deal with <code>Object</code> arrays and with primitive arrays.</p>
 *
 * <p>If the input array is <code>null</code>, <code>0</code> is returned.</p>
 *
 * <pre>//www .jav  a  2s. c o m
 * ArrayUtils.getLength(null)            = 0
 * ArrayUtils.getLength([])              = 0
 * ArrayUtils.getLength([null])          = 1
 * ArrayUtils.getLength([true, false])   = 2
 * ArrayUtils.getLength([1, 2, 3])       = 3
 * ArrayUtils.getLength(["a", "b", "c"]) = 3
 * </pre>
 *
 * @param array  the array to retrieve the length from, may be null
 * @return The length of the array, or <code>0</code> if the array is <code>null</code>
 * @throws IllegalArgumentException if the object arguement is not an array.
 * @since 2.1
 */
public static int getLength(Object array) {
    if (array == null) {
        return 0;
    }
    return Array.getLength(array);
}

From source file:fi.jumi.core.util.EqualityMatchers.java

private static String findDifference(String path, Object obj1, Object obj2) {
    if (obj1 == null || obj2 == null) {
        return obj1 == obj2 ? null : path;
    }//from   www .  ja v a  2  s.  c o  m
    if (obj1.getClass() != obj2.getClass()) {
        return path;
    }

    // collections have a custom equals, but we want deep equality on every collection element
    // TODO: support other collection types? comparing Sets should be order-independent
    if (obj1 instanceof List) {
        List<?> col1 = (List<?>) obj1;
        List<?> col2 = (List<?>) obj2;

        int size1 = col1.size();
        int size2 = col2.size();
        if (size1 != size2) {
            return path + ".size()";
        }

        for (int i = 0; i < Math.min(size1, size2); i++) {
            String diff = findDifference(path + ".get(" + i + ")", col1.get(i), col2.get(i));
            if (diff != null) {
                return diff;
            }
        }
        return null;
    }

    // use custom equals method if exists
    try {
        Method equals = obj1.getClass().getMethod("equals", Object.class);
        if (equals.getDeclaringClass() != Object.class) {
            return obj1.equals(obj2) ? null : path;
        }
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }

    // arrays
    if (obj2.getClass().isArray()) {
        int length1 = Array.getLength(obj1);
        int length2 = Array.getLength(obj2);
        if (length1 != length2) {
            return path + ".length";
        }

        for (int i = 0; i < Math.min(length1, length2); i++) {
            String diff = findDifference(path + "[" + i + "]", Array.get(obj1, i), Array.get(obj2, i));
            if (diff != null) {
                return diff;
            }
        }
        return null;
    }

    // structural equality
    for (Class<?> cl = obj2.getClass(); cl != null; cl = cl.getSuperclass()) {
        for (Field field : cl.getDeclaredFields()) {
            try {
                String diff = findDifference(path + "." + field.getName(),
                        FieldUtils.readField(field, obj1, true), FieldUtils.readField(field, obj2, true));
                if (diff != null) {
                    return diff;
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
    return null;
}

From source file:ArrayDemo.java

/** 
 * Print out 2 arrays in columnar format.
 *
 * @param first The array for the first column.
 * @param second The array for the second column.
 *
 * @throws IllegalArgumentException __UNDOCUMENTED__
 *//* w  w w . j av  a2s .  c  o  m*/
public static void outputArrays(final Object first, final Object second) {
    if (!first.getClass().isArray()) {
        throw new IllegalArgumentException("first is not an array.");
    }
    if (!second.getClass().isArray()) {
        throw new IllegalArgumentException("second is not an array.");
    }

    final int lengthFirst = Array.getLength(first);
    final int lengthSecond = Array.getLength(second);
    final int length = Math.max(lengthFirst, lengthSecond);

    for (int idx = 0; idx < length; idx++) {
        System.out.print("[" + idx + "]\t");
        if (idx < lengthFirst) {
            System.out.print(Array.get(first, idx) + "\t\t");
        } else {
            System.out.print("\t\t");
        }
        if (idx < lengthSecond) {
            System.out.print(Array.get(second, idx) + "\t");
        }
        System.out.println();
    }
}

From source file:org.springmodules.validation.util.condition.collection.MaxSizeCollectionCondition.java

/**
 * Checks whether the length of the given array is smaller than or equals the maximum size associated
 * with this condition./*from ww w .  j  a va  2 s .c o  m*/
 *
 * @param array The array to be checked.
 * @return <code>true</code> if the length of the given array is smaller than or equals the maximum size
 *         associated with this condition, <code>false</code> otherwise.
 */
protected boolean checkArray(Object array) {
    return Array.getLength(array) <= maxSize;
}

From source file:org.springmodules.validation.util.condition.collection.MinSizeCollectionCondition.java

/**
 * Checks whether the length of the given array is greater than or equals the minimum size associated
 * with this condition.//from   w  ww.  j av a 2s.c  om
 *
 * @param array The array to be checked.
 * @return <code>true</code> if the length of the given array is greater than or equals the minimum size
 *         associated with this condition, <code>false</code> otherwise.
 */
protected boolean checkArray(Object array) {
    return Array.getLength(array) >= minSize;
}

From source file:com.sworddance.util.CUtilities.java

/**
 * size of object//from   ww  w  .  ja  va2 s .c o  m
 * @param object {@link Map}, {@link Collection}, Array, {@link CharSequence}
 * @return 0 if null
 */
@SuppressWarnings("unchecked")
public static int size(Object object) {
    int total = 0;
    if (object != null) {
        if (object instanceof Map) {
            total = ((Map) object).size();
        } else if (object instanceof Collection) {
            total = ((Collection) object).size();
        } else if (object.getClass().isArray()) {
            total = Array.getLength(object);
        } else if (object instanceof CharSequence) {
            total = ((CharSequence) object).length();
        } else if (object instanceof Iterable) {
            Iterator it = ((Iterable) object).iterator();
            while (it.hasNext()) {
                total++;
                it.next();
            }
        } else {
            throw new ApplicationIllegalArgumentException(
                    "Unsupported object type: " + object.getClass().getName());
        }
    }
    return total;
}