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:ome.util.ModelMapper.java

/**
 * known immutables are return unchanged.
 * /*from  w  w w  . j  a  v a 2  s  .  c  om*/
 * @param current
 * @return a possibly uninitialized object which will be finalized as the
 *         object graph is walked.
 */
public Object findTarget(Object current) {

    // IMMUTABLES
    if (null == current || current instanceof Number || current instanceof String || current instanceof Boolean
            || current instanceof Timestamp || current instanceof Class) {
        return current;
    }

    Object target = model2target.get(current);
    if (null == target) {
        Class currentType = current.getClass();
        Class targetType = null;

        if (currentType.isArray()) {

            Class componentType = null;
            try {
                int length = Array.getLength(current);
                componentType = currentType.getComponentType();
                target = Array.newInstance(componentType, length);
                for (int i = 0; i < length; i++) {
                    Object currentValue = Array.get(current, i);
                    Object targetValue = this.filter("ARRAY", currentValue);
                    Array.set(target, i, targetValue);
                }
            } catch (Exception e) {
                log.error("Error creating new array of type " + componentType, e);
                throwOnNewInstanceException(current, componentType, e);
            }

        } else {
            targetType = findClass(currentType);

            if (null == targetType) {
                throw new InternalException("Cannot handle type:" + current);
            }

            try {
                target = targetType.newInstance();
            } catch (Exception e) {
                log.error("Error creating new instance of target type" + current, e);
                throwOnNewInstanceException(current, targetType, e);
            }

        }
        model2target.put(current, target);
    }
    return target;
}

From source file:org.ldaptive.beans.spring.SpelAttributeValueMutator.java

/**
 * Uses the configured expression and evaluation context to retrieve values
 * from the supplied object. Values are the placed in a collection and
 * returned./*  w  w w .  j av  a  2  s . c  o m*/
 *
 * @param  <T>  either String or byte[]
 * @param  object  to get values from
 * @param  type  of objects to place in the collection
 *
 * @return  values in the supplied object
 */
protected <T> Collection<T> getValues(final Object object, final Class<T> type) {
    Collection<T> values = null;
    final Object converted = expression.getValue(evaluationContext, object);
    if (converted != null) {
        if (converted instanceof byte[] || converted instanceof char[]) {
            values = createCollection(List.class, 1);

            final T value = convertValue(converted, converted.getClass(), type);
            if (value != null) {
                values.add(value);
            }
        } else if (converted.getClass().isArray()) {
            final int length = Array.getLength(converted);
            values = createCollection(List.class, length);
            for (int i = 0; i < length; i++) {
                final Object o = Array.get(converted, i);
                if (o != null) {
                    final T value = convertValue(o, o.getClass(), type);
                    if (value != null) {
                        values.add(value);
                    }
                }
            }
        } else if (Collection.class.isAssignableFrom(converted.getClass())) {
            final Collection<?> col = (Collection<?>) converted;
            values = createCollection(converted.getClass(), col.size());
            for (Object o : col) {
                if (o != null) {
                    final T value = convertValue(o, o.getClass(), type);
                    if (value != null) {
                        values.add(value);
                    }
                }
            }
        } else {
            values = createCollection(List.class, 1);

            final T value = convertValue(converted, converted.getClass(), type);
            if (value != null) {
                values.add(value);
            }
        }
    }
    return values;
}

From source file:org.apache.struts2.components.ListUIBean.java

public void evaluateExtraParams() {
    Object value = null;//from   ww w .  ja v  a  2  s.c om

    if (list == null) {
        list = parameters.get("list");
    }

    if (list instanceof String) {
        value = findValue((String) list);
    } else if (list instanceof Collection) {
        value = list;
    } else if (MakeIterator.isIterable(list)) {
        value = MakeIterator.convert(list);
    }
    if (value == null) {
        if (throwExceptionOnNullValueAttribute) {
            // will throw an exception if not found
            value = findValue((list == null) ? (String) list : list.toString(), "list",
                    "The requested list key '" + list
                            + "' could not be resolved as a collection/array/map/enumeration/iterator type. "
                            + "Example: people or people.{name}");
        } else {
            // ww-1010, allows value with null value to be compatible with ww
            // 2.1.7 behaviour
            value = findValue((list == null) ? (String) list : list.toString());
        }
    }

    if (value instanceof Collection) {
        addParameter("list", value);
    } else {
        addParameter("list", MakeIterator.convert(value));
    }

    if (value instanceof Collection) {
        addParameter("listSize", ((Collection) value).size());
    } else if (value instanceof Map) {
        addParameter("listSize", ((Map) value).size());
    } else if (value != null && value.getClass().isArray()) {
        addParameter("listSize", Array.getLength(value));
    }

    if (listKey != null) {
        listKey = stripExpressionIfAltSyntax(listKey);
        addParameter("listKey", listKey);
    } else if (value instanceof Map) {
        addParameter("listKey", "key");
    }

    if (listValueKey != null) {
        listValueKey = stripExpressionIfAltSyntax(listValueKey);
        addParameter("listValueKey", listValueKey);
    }

    if (listValue != null) {
        listValue = stripExpressionIfAltSyntax(listValue);
        addParameter("listValue", listValue);
    } else if (value instanceof Map) {
        addParameter("listValue", "value");
    }

    if (listLabelKey != null) {
        listLabelKey = stripExpressionIfAltSyntax(listLabelKey);
        addParameter("listLabelKey", listLabelKey);
    }

    if (StringUtils.isNotBlank(listCssClass)) {
        addParameter("listCssClass", listCssClass);
    }

    if (StringUtils.isNotBlank(listCssStyle)) {
        addParameter("listCssStyle", listCssStyle);
    }

    if (StringUtils.isNotBlank(listTitle)) {
        addParameter("listTitle", listTitle);
    }
}

From source file:com.proctorcam.proctorserv.HashedAuthenticator.java

protected static Object[] getArray(Object arr) {
    // Does not convert if not necessary
    if (arr instanceof Object[])
        return (Object[]) arr;

    int arrlength = Array.getLength(arr);
    Object[] outputArray = new Object[arrlength];
    for (int i = 0; i < arrlength; ++i) {
        outputArray[i] = Array.get(arr, i);
    }/*from  w  w w . j  av a 2 s  .c o m*/
    return outputArray;
}

From source file:com.feilong.core.lang.ObjectUtilTemp.java

/**
 * ?? {@link java.util.Iterator}./*w w w. j  a  v  a  2  s  . co m*/
 * <p>
 * ??,,???with no copying<br>
 * ?, ClassCastException  ,Rats -- ,arrayList ?arrayList.iterator()
 * </p>
 * <p>
 * <b>:</b>{@link Arrays#asList(Object...)} list {@link Array}  ArrayList,
 * {@link java.util.AbstractList#add(int, Object)} ,<br>
 * listadd?, {@link java.lang.UnsupportedOperationException}
 * </p>
 * 
 * @param <T>
 *            the generic type
 * @param arrays
 *            ,? , 
 * @return  (null == arrays)  null;<br>
 *         ?arrays?Object[], {@link Arrays#asList(Object...)}?list,? {@link List#iterator()
 *         t}<br>
 *         ,? Object[],?, {@link Array#getLength(Object)}?, {@link Array#get(Object, int)} list
 * @see Arrays#asList(Object...)
 * @see Array#getLength(Object)
 * @see Array#get(Object, int)
 * @see List#iterator()
 * @deprecated
 */
@Deprecated
@SuppressWarnings({ "unchecked" })
public static <T> Iterator<T> toIterator(Object arrays) {
    if (null == arrays) {
        return null;
    }
    List<T> list = null;
    try {
        // ??,,???with no copying
        Object[] objArrays = (Object[]) arrays;
        list = (List<T>) toList(objArrays);
    } catch (ClassCastException e) {
        LOGGER.debug("arrays can not cast to Object[],maybe primitive type,values is:{},{}", arrays,
                e.getMessage());
        // Rats -- 
        int length = Array.getLength(arrays);
        list = new ArrayList<T>(length);
        for (int i = 0; i < length; ++i) {
            Object object = Array.get(arrays, i);
            list.add((T) object);
        }
    }
    return list.iterator();
}

From source file:org.nabucco.alfresco.enhScriptEnv.common.script.converter.general.ArrayConverter.java

/**
 * {@inheritDoc}//from  w  w w.  ja v  a2s .  c o m
 */
@Override
public boolean canConvertValueForScript(final Object value, final ValueConverter globalDelegate,
        final Class<?> expectedClass) {
    boolean canConvert = expectedClass.isArray();

    if (canConvert) {
        final Class<?> componentClass = expectedClass.getComponentType();
        if (value instanceof Iterable<?>) {
            final Collection<?> coll = (Collection<?>) value;
            for (final Object element : coll) {
                canConvert = canConvert && globalDelegate.canConvertValueForScript(element, componentClass);

                if (!canConvert) {
                    break;
                }
            }
        } else if (value.getClass().isArray()) {
            final int length = Array.getLength(value);
            for (int idx = 0; idx < length && canConvert; idx++) {
                canConvert = canConvert
                        && globalDelegate.canConvertValueForScript(Array.get(value, idx), componentClass);
            }
        } else {
            canConvert = false;
        }
    }

    return canConvert;
}

From source file:ObjectStack.java

/**
 * Copy data after array resize. This just copies the entire contents of the
 * old array to the start of the new array. It should be overridden in cases
 * where data needs to be rearranged in the array after a resize.
 * /*  ww  w.jav a 2  s .c o m*/
 * @param base original array containing data
 * @param grown resized array for data
 */
private void resizeCopy(Object base, Object grown) {
    System.arraycopy(base, 0, grown, 0, Array.getLength(base));
}

From source file:com.smallchill.core.toolbox.Func.java

/**
 * ??//from  w ww.ja v a  2 s.c o m
 * 
 * @param obj
 *            
 * @param element
 *            
 * @return ??
 */
public static boolean contains(Object obj, Object element) {
    if (obj == null) {
        return false;
    }
    if (obj instanceof String) {
        if (element == null) {
            return false;
        }
        return ((String) obj).contains(element.toString());
    }
    if (obj instanceof Collection) {
        return ((Collection<?>) obj).contains(element);
    }
    if (obj instanceof Map) {
        return ((Map<?, ?>) obj).values().contains(element);
    }

    if (obj instanceof Iterator) {
        Iterator<?> iter = (Iterator<?>) obj;
        while (iter.hasNext()) {
            Object o = iter.next();
            if (equals(o, element)) {
                return true;
            }
        }
        return false;
    }
    if (obj instanceof Enumeration) {
        Enumeration<?> enumeration = (Enumeration<?>) obj;
        while (enumeration.hasMoreElements()) {
            Object o = enumeration.nextElement();
            if (equals(o, element)) {
                return true;
            }
        }
        return false;
    }
    if (obj.getClass().isArray() == true) {
        int len = Array.getLength(obj);
        for (int i = 0; i < len; i++) {
            Object o = Array.get(obj, i);
            if (equals(o, element)) {
                return true;
            }
        }
    }
    return false;
}

From source file:com.evolveum.midpoint.prism.util.CloneUtil.java

private static <T> T cloneArray(T orig) {
    int length = Array.getLength(orig);
    T clone = (T) Array.newInstance(orig.getClass().getComponentType(), length);
    System.arraycopy(orig, 0, clone, 0, length);
    return clone;
}

From source file:au.com.dw.testdatacapturej.builder.LineBuilder.java

/**
 * Generate a constructor line for the test data class which is an array.
 * //from  w w  w  .  j a  va2 s .com
 * If the array is:
 *   Object[]
 * Then should generate:
 *   Object[] objectArray = new Object[10];
 *  
 * @param builder
 * @param info The ObjectInfo for the object that requires the constructor line to be generated
 */
public void createArrayConstructorLine(LogBuilder builder, ObjectInfo info) {
    // extra info required for an array constructor as opposed to an object constructor
    Object array = info.getValue();
    String arrayType = array.getClass().getComponentType().getName();
    int initialSize = Array.getLength(array);

    //StringBuilder constructorLineBuilder = new StringBuilder();

    builder.process(arrayType);
    builder.append("[] ");

    builder.append(info.getClassFieldName());
    builder.append(info.getClassFieldNameIndex());

    builder.append(" = new ");
    builder.process(arrayType);
    builder.append("[");
    if (initialSize >= 0) {
        builder.append(initialSize);
    }
    builder.append("];");
}