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.bstek.dorado.view.type.property.MappingPropertyOutputter.java

protected void outputArray(Mapping mapping, Object elements, OutputContext context) throws Exception {
    String keyProperty = StringUtils.defaultString(mapping.getKeyProperty(), "key");
    String valueProperty = StringUtils.defaultString(mapping.getValueProperty(), "value");

    JsonBuilder json = context.getJsonBuilder();
    json.array();//w w w.  j  a v a2s  .  c  o  m

    int length = Array.getLength(elements);
    for (int i = 0; i < length; i++) {
        Object element = Array.get(elements, i);
        EntityWrapper entity = EntityWrapper.create(element);
        json.object();

        json.key("key");
        outputData(entity.get(keyProperty), context);
        json.endKey();

        json.key("value");
        outputData(entity.get(valueProperty), context);
        json.endKey();

        json.endObject();
    }
    json.endArray();
}

From source file:es.caib.zkib.jxpath.util.BasicTypeConverter.java

/**
 * Returns true if it can convert the supplied
 * object to the specified class./*w  w  w. j ava 2 s  .c o m*/
 * @param object to check
 * @param toType prospective destination class
 * @return boolean
 */
public boolean canConvert(Object object, final Class toType) {
    if (object == null) {
        return true;
    }
    final Class useType = TypeUtils.wrapPrimitive(toType);
    Class fromType = object.getClass();

    if (useType.isAssignableFrom(fromType)) {
        return true;
    }

    if (useType == String.class) {
        return true;
    }

    if (object instanceof Boolean && (Number.class.isAssignableFrom(useType)
            || "java.util.concurrent.atomic.AtomicBoolean".equals(useType.getName()))) {
        return true;
    }
    if (object instanceof Number && (Number.class.isAssignableFrom(useType) || useType == Boolean.class)) {
        return true;
    }
    if (object instanceof String && (useType == Boolean.class || useType == Character.class
            || useType == Byte.class || useType == Short.class || useType == Integer.class
            || useType == Long.class || useType == Float.class || useType == Double.class)) {
        return true;
    }
    if (fromType.isArray()) {
        // Collection -> array
        if (useType.isArray()) {
            Class cType = useType.getComponentType();
            int length = Array.getLength(object);
            for (int i = 0; i < length; i++) {
                Object value = Array.get(object, i);
                if (!canConvert(value, cType)) {
                    return false;
                }
            }
            return true;
        }
        if (Collection.class.isAssignableFrom(useType)) {
            return canCreateCollection(useType);
        }
        if (Array.getLength(object) > 0) {
            Object value = Array.get(object, 0);
            return canConvert(value, useType);
        }
        return canConvert("", useType);
    }
    if (object instanceof Collection) {
        // Collection -> array
        if (useType.isArray()) {
            Class cType = useType.getComponentType();
            Iterator it = ((Collection) object).iterator();
            while (it.hasNext()) {
                Object value = it.next();
                if (!canConvert(value, cType)) {
                    return false;
                }
            }
            return true;
        }
        if (Collection.class.isAssignableFrom(useType)) {
            return canCreateCollection(useType);
        }
        if (((Collection) object).size() > 0) {
            Object value;
            if (object instanceof List) {
                value = ((List) object).get(0);
            } else {
                Iterator it = ((Collection) object).iterator();
                value = it.next();
            }
            return canConvert(value, useType);
        }
        return canConvert("", useType);
    }
    if (object instanceof NodeSet) {
        return canConvert(((NodeSet) object).getValues(), useType);
    }
    if (object instanceof Pointer) {
        return canConvert(((Pointer) object).getValue(), useType);
    }
    return ConvertUtils.lookup(useType) != null;
}

From source file:de.alpharogroup.lang.ObjectExtensions.java

/**
 * Try to clone the given object.//from   w w  w.  jav  a2s .  c o m
 *
 * @param object
 *            The object to clone.
 * @return The cloned object or null if the clone process failed.
 * @throws NoSuchMethodException
 *             the no such method exception
 * @throws SecurityException
 *             Thrown if the security manager indicates a security violation.
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws ClassNotFoundException
 *             the class not found exception
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Object cloneObject(final Object object)
        throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, ClassNotFoundException, InstantiationException, IOException {
    Object clone = null;
    // Try to clone the object if it implements Serializable.
    if (object instanceof Serializable) {
        clone = SerializedObjectUtils.copySerializedObject((Serializable) object);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object if it is Cloneble.
    if (clone == null && object instanceof Cloneable) {

        if (object.getClass().isArray()) {
            final Class<?> componentType = object.getClass().getComponentType();
            if (componentType.isPrimitive()) {
                int length = Array.getLength(object);
                clone = Array.newInstance(componentType, length);
                while (length-- > 0) {
                    Array.set(clone, length, Array.get(object, length));
                }
            } else {
                clone = ((Object[]) object).clone();
            }
            if (clone != null) {
                return clone;
            }
        }
        final Class<?> clazz = object.getClass();
        final Method cloneMethod = clazz.getMethod("clone", (Class[]) null);
        clone = cloneMethod.invoke(object, (Object[]) null);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object by copying all his properties with
    // the BeanUtils.copyProperties() method.
    if (clone == null) {
        clone = ReflectionUtils.getNewInstance(object);
        BeanUtils.copyProperties(clone, object);
    }
    return clone;
}

From source file:Main.java

/**
 Hash code for an Object./*w  w w .ja  v  a  2  s  .  co  m*/
        
 <P><tt>aObject</tt> is a possibly-null object field, and possibly an array.
        
 If <tt>aObject</tt> is an array, then each element may be a primitive
 or a possibly-null object.
 */
public static int hash(int aSeed, Object aObject) {

    int result = aSeed;

    if (aObject == null) {

        result = hash(result, 0);
    } else if (!isArray(aObject)) {

        result = hash(result, aObject.hashCode());
    } else {

        int length = Array.getLength(aObject);

        for (int idx = 0; idx < length; ++idx) {

            Object item = Array.get(aObject, idx);

            //recursive call!
            result = hash(result, item);
        }
    }

    return result;
}

From source file:com.bxf.hradmin.common.utils.QueryParameterTransformer.java

@SuppressWarnings("rawtypes")
private static Object[] asArray(Object value) {
    if (value.getClass().isArray()) {
        Object[] result = new Object[Array.getLength(value)];
        for (int i = 0; i < result.length; ++i) {
            result[i] = Array.get(value, i);
        }/*from  w  w w  .j  a  v a  2 s  .  co  m*/
        return result;
    } else if (value instanceof Collection) {
        return ((Collection) value).toArray();
    }
    return new Object[] { value };
}

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

public static char[] convertToCharArray(final Object array) {
    if (array == null) {
        return null;
    }// w  w  w  . ja va  2  s . c  om
    if (array instanceof char[]) {
        return (char[]) array;
    }
    if (array instanceof Character[]) {
        return ArrayUtils.toPrimitive((Character[]) array);
    }
    final char[] newArray = new char[Array.getLength(array)];
    for (int i = 0; i < newArray.length; i++) {
        final Object obj = Array.get(array, i);
        if (obj instanceof Character) {
            newArray[i] = (Character) Array.get(array, i);
        } else {
            newArray[i] = (char) ((Number) Array.get(array, i)).byteValue();
        }
    }
    return newArray;
}

From source file:com.github.ibole.infrastructure.persistence.db.mybatis.pagination.PagingParametersFinder.java

/**
 * Find whether it contains the <code>PaginationCriteria</code> object in the array.
 *
 * @param array the array./*  w w w  .  jav a2  s.  co m*/
 * @return PageQuery
 */
private PagingCriteria findCriteriaFromArray(Object array) {
    if (searchMap.containsKey(array)) {
        return null;
    }

    Object object;
    PagingCriteria pc;
    for (int i = 0; i < Array.getLength(array); i++) {
        object = Array.get(array, i);
        pc = findCriteriaFromObject(object);
        if (pc != null) {
            searchMap.put(array, SqlHelper.EMPTY);
            return pc;
        }
    }
    searchMap.put(array, SqlHelper.EMPTY);
    return null;
}

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

@Override
public String checkPositionValid(Object position) {
    try {//  www  . ja  v  a 2  s  . co m
        if (position instanceof double[] || position instanceof Double[] || position instanceof PyFloat[]) {
            if (Array.getLength(position) == this.currentPosition.length) {
                return null;
            }
        } else if (position instanceof PyArray) {
            if (((PyArray) position).__len__() == this.currentPosition.length) {
                return null;
            }
        } else if (position instanceof PyList) {
            if (((PyList) position).__len__() == this.currentPosition.length) {
                return null;
            }
        } else if (position instanceof Number && this.currentPosition.length == 1) {
            return null;
        }
        return "position must be an array of doubles of the correct length";
    } catch (NumberFormatException e) {
        return e.getMessage();
    }
}

From source file:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Returns the length of the supplied collection. If the supplied object
 * is not a collection, returns 1. If collection is null, returns 0.
 * @param collection to check/*from   ww  w.j  ava  2  s  .com*/
 * @return int
 */
public static int getLength(Object collection) {
    if (collection == null) {
        return 0;
    }
    collection = getValue(collection);
    if (collection.getClass().isArray()) {
        return Array.getLength(collection);
    }
    if (collection instanceof Collection) {
        return ((Collection) collection).size();
    }
    return 1;
}

From source file:org.apache.axis.encoding.ser.BeanPropertyTarget.java

/**
 * set the bean property with specified value
 * @param value is the value.//from   w  w w . j av a 2 s.  c om
 */
public void set(Object value) throws SAXException {

    try {
        // Set the value on the bean property. 
        // Use the indexed property method if the 
        // index is set.
        if (index < 0) {
            pd.set(object, value);
        } else {
            pd.set(object, index, value);
        }
    } catch (Exception e) {

        try {
            // If an exception occurred, 
            // see it the value can be converted into
            // the expected type.
            Class type = pd.getType();

            if (value.getClass().isArray() && value.getClass().getComponentType().isPrimitive()
                    && type.isArray() && type.getComponentType().equals(Object.class)) {
                //we make our own array type here.
                type = Array.newInstance(JavaUtils.getWrapperClass(value.getClass().getComponentType()), 0)
                        .getClass();
            }

            if (JavaUtils.isConvertable(value, type)) {
                value = JavaUtils.convert(value, type);
                if (index < 0)
                    pd.set(object, value);
                else
                    pd.set(object, index, value);
            } else {
                // It is possible that an indexed
                // format was expected, but the
                // entire array was sent.  In such 
                // cases traverse the array and 
                // call the setter for each item.
                if (index == 0 && value.getClass().isArray() && !type.getClass().isArray()) {
                    for (int i = 0; i < Array.getLength(value); i++) {
                        Object item = JavaUtils.convert(Array.get(value, i), type);
                        pd.set(object, i, item);
                    }
                } else {
                    // Can't proceed.  Throw an exception that
                    // will be caught in the catch block below.
                    throw e;
                }
            }
        } catch (Exception ex) {
            // Throw a SAX exception with an informative
            // message.
            String field = pd.getName();
            if (index >= 0) {
                field += "[" + index + "]";
            }
            if (log.isErrorEnabled()) {
                //TODO: why is this just logged on the server-side and not thrown back to the client???
                String valueType = "null";
                if (value != null)
                    valueType = value.getClass().getName();
                log.error(Messages.getMessage("cantConvert02", new String[] { valueType, field,
                        (index >= 0) ? pd.getType().getComponentType().getName() : pd.getType().getName() }));
            }
            if (ex instanceof InvocationTargetException) {
                Throwable t = ((InvocationTargetException) ex).getTargetException();
                if (t != null) {
                    String classname = this.object.getClass().getName();
                    //show the context where this exception occured.
                    throw new SAXException(Messages.getMessage("cantConvert04", new String[] { classname, field,
                            (value == null) ? null : value.toString(), t.getMessage() }));
                }
            }
            throw new SAXException(ex);
        }
    }
}