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:com.vmware.af.interop.Validate.java

/**
 * Check whether given object value is empty. Depending on argument runtime
 * type <i>empty</i> means:/*w ww.j  a va2 s .  c  o m*/
 * <ul>
 * <li>for java.lang.String type - {@code null} value or empty string</li>
 * <li>for array type - {@code null} value or zero length array</li>
 * <li>for any other type - {@code null} value</li>
 * </ul>
 * <p>
 * Note that java.lang.String values should be handled by
 * {@link #isEmpty(String)}
 * </p>
 *
 * @param obj
 *           any object or {@code null}
 *
 * @return {@code true} when the object value is {@code null} or empty array
 */
public static boolean isEmpty(Object obj) {

    if (obj == null) {
        return true;
    }

    if (obj.getClass().equals(String.class)) {
        return ((String) obj).isEmpty();
    }

    if (obj.getClass().isArray()) {
        return Array.getLength(obj) == 0;
    }

    if (obj instanceof java.util.Collection<?>) {
        return ((java.util.Collection<?>) obj).isEmpty();
    }

    final String message = "String, java.lang.Array or java.util.Collection " + "expected but "
            + obj.getClass().getName() + " was found ";

    getLog().error(message);
    throw new IllegalArgumentException(message);
}

From source file:Main.java

public static Map<String, Object> getProperties(Object object, boolean includeSuperClasses, boolean deepCopy) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    if (object == null) {
        return map;
    }//  w w w .  j  av a2s .c om

    Class<?> objectClass = object.getClass();
    Method[] methods = includeSuperClasses ? objectClass.getMethods() : objectClass.getDeclaredMethods();
    for (Method method : methods) {
        if (method.getParameterTypes().length == 0 && !method.getReturnType().equals(Void.TYPE)) {
            String methodName = method.getName();
            String propertyName = "";
            if (methodName.startsWith("get")) {
                propertyName = methodName.substring(3);
            } else if (methodName.startsWith("is")) {
                propertyName = methodName.substring(2);
            }
            if (propertyName.length() > 0 && Character.isUpperCase(propertyName.charAt(0))) {
                propertyName = Character.toLowerCase(propertyName.charAt(0)) + propertyName.substring(1);

                Object value = null;
                try {
                    value = method.invoke(object);
                } catch (Exception e) {
                }

                Object value2 = value;

                if (!deepCopy) {
                    map.put(propertyName, value);
                } else {
                    if (isSimpleObject(value)) {
                        map.put(propertyName, value);
                    } else if (value instanceof Map) {
                        Map<String, Object> submap = new HashMap<String, Object>();
                        for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
                            submap.put(String.valueOf(entry.getKey()),
                                    convertObject(entry.getValue(), includeSuperClasses));
                        }
                        map.put(propertyName, submap);
                    } else if (value instanceof Iterable) {
                        List<Object> sublist = new ArrayList<Object>();
                        for (Object v : (Iterable<?>) object) {
                            sublist.add(convertObject(v, includeSuperClasses));
                        }
                        map.put(propertyName, sublist);
                    } else if (value.getClass().isArray()) {
                        List<Object> sublist = new ArrayList<Object>();
                        int length = Array.getLength(value);
                        for (int i = 0; i < length; i++) {
                            sublist.add(convertObject(Array.get(value, i), includeSuperClasses));
                        }
                        map.put(propertyName, sublist);
                    } else {
                        map.put(propertyName, getProperties(value, includeSuperClasses, deepCopy));
                    }
                }
            }
        }
    }

    return map;
}

From source file:org.atemsource.atem.impl.common.attribute.collection.ArrayAttributeImpl.java

@Override
public Collection getElements(Object entity) {
    final Object array = getValue(entity);
    List arrayList = new ArrayList();
    if (array == null) {
        return null;
    } else {/*from  w  w  w.  j  ava2 s.  co  m*/
        for (int index = 0; index < Array.getLength(array); index++) {
            arrayList.add(Array.get(array, index));
        }
        return arrayList;
    }
}

From source file:net.henryco.opalette.api.utils.Utils.java

@SuppressWarnings("unchecked")
public static <T> T arrayFlatCopy(Object a) {
    int l = Array.getLength(a);
    Object arr = java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), l);
    System.arraycopy(a, 0, arr, 0, l);
    return (T) arr;
}

From source file:com.espertech.esper.epl.enummethod.eval.EnumEvalSequenceEqual.java

public Object evaluateEnumMethod(EventBean[] eventsLambda, Collection target, boolean isNewData,
        ExprEvaluatorContext context) {//from w  ww . j a v a2 s.com
    Object otherObj = this.getInnerExpression().evaluate(eventsLambda, isNewData, context);

    if (otherObj == null) {
        return false;
    }
    if (!(otherObj instanceof Collection)) {
        if (otherObj.getClass().isArray()) {
            if (target.size() != Array.getLength(otherObj)) {
                return false;
            }

            if (target.isEmpty()) {
                return true;
            }

            Iterator oneit = target.iterator();
            for (int i = 0; i < target.size(); i++) {
                Object first = oneit.next();
                Object second = Array.get(otherObj, i);

                if (first == null) {
                    if (second != null) {
                        return false;
                    }
                    continue;
                }
                if (second == null) {
                    return false;
                }

                if (!first.equals(second)) {
                    return false;
                }
            }

            return true;
        } else {
            log.warn(
                    "Enumeration method 'sequenceEqual' expected a Collection-type return value from its parameter but received '"
                            + otherObj.getClass() + "'");
            return false;
        }
    }

    Collection other = (Collection) otherObj;
    if (target.size() != other.size()) {
        return false;
    }

    if (target.isEmpty()) {
        return true;
    }

    Iterator oneit = target.iterator();
    Iterator twoit = other.iterator();
    for (int i = 0; i < target.size(); i++) {
        Object first = oneit.next();
        Object second = twoit.next();

        if (first == null) {
            if (second != null) {
                return false;
            }
            continue;
        }
        if (second == null) {
            return false;
        }

        if (!first.equals(second)) {
            return false;
        }
    }

    return true;
}

From source file:ObjectAnalyzerTest.java

/**
 * Converts an object to a string representation that lists all fields.
 * //from w w  w  .ja  v  a  2  s. co m
 * @param obj
 *          an object
 * @return a string with the object's class name and all field names and
 *         values
 */
public String toString(Object obj) {
    if (obj == null)
        return "null";
    if (visited.contains(obj))
        return "...";
    visited.add(obj);
    Class cl = obj.getClass();
    if (cl == String.class)
        return (String) obj;
    if (cl.isArray()) {
        String r = cl.getComponentType() + "[]{";
        for (int i = 0; i < Array.getLength(obj); i++) {
            if (i > 0)
                r += ",";
            Object val = Array.get(obj, i);
            if (cl.getComponentType().isPrimitive())
                r += val;
            else
                r += toString(val);
        }
        return r + "}";
    }

    String r = cl.getName();
    // inspect the fields of this class and all superclasses
    do {
        r += "[";
        Field[] fields = cl.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        // get the names and values of all fields
        for (Field f : fields) {
            if (!Modifier.isStatic(f.getModifiers())) {
                if (!r.endsWith("["))
                    r += ",";
                r += f.getName() + "=";
                try {
                    Class t = f.getType();
                    Object val = f.get(obj);
                    if (t.isPrimitive())
                        r += val;
                    else
                        r += toString(val);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        r += "]";
        cl = cl.getSuperclass();
    } while (cl != null);

    return r;
}

From source file:ArrayGrowTest.java

/**
 * A convenience method to print all elements in an array
 * /*from w ww.j  a  va 2s .  c om*/
 * @param a
 *          the array to print. It can be an object array or a primitive type
 *          array
 */
static void arrayPrint(Object a) {
    Class cl = a.getClass();
    if (!cl.isArray())
        return;
    Class componentType = cl.getComponentType();
    int length = Array.getLength(a);
    System.out.print(componentType.getName() + "[" + length + "] = { ");
    for (int i = 0; i < Array.getLength(a); i++)
        System.out.print(Array.get(a, i) + " ");
    System.out.println("}");
}

From source file:mil.jpeojtrs.sca.util.PrimitiveArrayUtils.java

public static int[] convertToIntArray(final Object array) {
    if (array == null) {
        return null;
    }//w  w w .j  a  va  2  s. co m
    if (array instanceof int[]) {
        return (int[]) array;
    }
    if (array instanceof Integer[]) {
        return ArrayUtils.toPrimitive((Integer[]) array);
    }
    final int[] newArray = new int[Array.getLength(array)];
    for (int i = 0; i < newArray.length; i++) {
        final Number val = (Number) Array.get(array, i);
        newArray[i] = val.intValue();
    }
    return newArray;
}

From source file:com.espertech.esper.epl.expression.dot.ExprDotEvalArrayGet.java

public Object evaluate(Object target, EventBean[] eventsPerStream, boolean isNewData,
        ExprEvaluatorContext exprEvaluatorContext) {
    if (target == null) {
        return null;
    }//from  w  ww  . j  ava  2  s. co  m

    Object index = indexExpression.evaluate(eventsPerStream, isNewData, exprEvaluatorContext);
    if (index == null) {
        return null;
    }
    if (!(index instanceof Integer)) {
        return null;
    }
    int indexNum = (Integer) index;

    if (Array.getLength(target) <= indexNum) {
        return null;
    }
    return Array.get(target, indexNum);
}

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

/**
 * Checks whether at least X objects in the given array adhere to the associated condition. X is determined
 * by the <code>getCount()</code> method call.
 *
 * @param array The array to be checked.
 * @return <code>true</code> if at least X objects in the given array adhere to the associated element condition,
 *         <code>false</code> otherwise.
 *//* w  w w  .  ja  v a2s  .  c om*/
protected boolean checkArray(Object array) {
    int counter = 0;
    for (int i = 0; i < Array.getLength(array); i++) {
        if (getElementCondition().check(Array.get(array, i))) {
            counter++;
        }
    }
    return counter >= getCount();
}