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.adobe.acs.commons.util.impl.ValueMapTypeConverter.java

private Object unwrapArray(Object wrapperArray, Class<?> primitiveType) {
    int length = Array.getLength(wrapperArray);
    Object primitiveArray = Array.newInstance(primitiveType, length);
    for (int i = 0; i < length; i++) {
        Array.set(primitiveArray, i, Array.get(wrapperArray, i));
    }//  w  ww  .ja v a2s.  c  om
    return primitiveArray;
}

From source file:com.blackbear.flatworm.ParseUtils.java

/**
 * Determine how best to add the {@code toAdd} instance to the collection found in {@code target} by seeing if either the {@code
 * Segment.addMethod} has a value or if {@code Segment.propertyName} has a value. If neither values exist then no action is taken.
 *
 * @param cardinality The {@link CardinalityBO} instance containing the configuration information.
 * @param target      The instance with the collection to which the {@code toAdd} instance is to be added.
 * @param toAdd       The instance to be added to the specified collection.
 * @throws FlatwormParserException should the attempt to add the {@code toAdd} instance to the specified collection fail for any
 *                                 reason.
 *///from w w  w. j a  va2s .c  o  m
public static void addValueToCollection(CardinalityBO cardinality, Object target, Object toAdd)
        throws FlatwormParserException {
    if (cardinality.getCardinalityMode() != CardinalityMode.SINGLE) {

        boolean addToCollection = true;
        PropertyDescriptor propDesc;

        try {
            propDesc = PropertyUtils.getPropertyDescriptor(target, cardinality.getPropertyName());
        } catch (Exception e) {
            // This should only happen via the XML configuration as the annotation configuration uses reflection to 
            // determine the property name. 
            throw new FlatwormParserException(String.format(
                    "Failed to read property %s on bean %s. Make sure the specified "
                            + "property-name is correct in the configuration for the record-element.",
                    cardinality.getPropertyName(), target.getClass().getName()), e);
        }

        if (cardinality.getCardinalityMode() == CardinalityMode.STRICT
                || cardinality.getCardinalityMode() == CardinalityMode.RESTRICTED) {

            try {
                Object currentValue = PropertyUtils.getProperty(target, cardinality.getPropertyName());
                int currentSize;

                if (Collection.class.isAssignableFrom(propDesc.getPropertyType())) {
                    currentSize = Collection.class.cast(currentValue).size();
                } else if (propDesc.getPropertyType().isArray()) {
                    currentSize = Array.getLength(currentValue);
                } else {
                    throw new FlatwormParserException(String.format(
                            "Bean %s has a Cardinality Mode of %s for property %s, "
                                    + "suggesting that it is an Array or some instance of java.util.Collection. However, the property type "
                                    + "is %s, which is not currently supported.",
                            target.getClass().getName(), cardinality.getCardinalityMode().name(),
                            cardinality.getPropertyName(), propDesc.getPropertyType().getName()));
                }

                addToCollection = currentSize < cardinality.getMaxCount() || cardinality.getMaxCount() < 0;

            } catch (Exception e) {
                throw new FlatwormParserException(String.format(
                        "Failed to load property %s on bean %s when determining if a "
                                + "value could be added to the collection.",
                        cardinality.getPropertyName(), target.getClass().getName()), e);
            }

            if (!addToCollection && cardinality.getCardinalityMode() == CardinalityMode.STRICT) {
                throw new FlatwormParserException(String.format(
                        "Cardinality limit of %d exceeded for property %s of bean %s "
                                + "with Cardinality Mode set to %s.",
                        cardinality.getMaxCount(), cardinality.getPropertyName(), target.getClass().getName(),
                        cardinality.getCardinalityMode().name()));
            }
        }

        // Add it if we have determined that's allowed.
        if (addToCollection) {

            // Need to make sure we have an add method for Arrays.
            // TODO - add ability to automatically expand an array - for now, use an addMethod or collections.
            if (StringUtils.isBlank(cardinality.getAddMethod()) && propDesc.getPropertyType().isArray()) {
                throw new FlatwormParserException(String.format(
                        "Bean %s with property %s is an Array and therefore an Add Method "
                                + "must be specified in the configuration so that an element can be properly added to the array. "
                                + "Auto-expanding an array is not yet supported.",
                        target.getClass().getName(), cardinality.getPropertyName()));
            }

            if (!StringUtils.isBlank(cardinality.getAddMethod())) {
                invokeAddMethod(target, cardinality.getAddMethod(), toAdd);
            } else if (!StringUtils.isBlank(cardinality.getPropertyName())) {
                addValueToCollection(target, cardinality.getPropertyName(), toAdd);
            }
        }
    } else {
        throw new FlatwormParserException(String.format(
                "Object %s attempted to be added to Object %s as part of a collection,"
                        + " but the configuration has it configured as a %s Cardinality Mode.",
                toAdd.getClass().getName(), target.getClass().getName(),
                cardinality.getCardinalityMode().name()));
    }
}

From source file:cz.vse.esper.XMLRenderer.java

private String renderAttElements(EventBean theEvent, int level, RendererMeta meta) {
    StringBuilder buf = new StringBuilder();

    GetterPair[] indexProps = meta.getIndexProperties();
    for (GetterPair indexProp : indexProps) {
        Object value = indexProp.getGetter().get(theEvent);

        if (value == null) {
            continue;
        }/* w w w  . j a  va 2 s .  c om*/
        if (!value.getClass().isArray()) {
            log.warn("Property '" + indexProp.getName() + "' returned a non-array object");
            continue;
        }
        for (int i = 0; i < Array.getLength(value); i++) {
            Object arrayItem = Array.get(value, i);

            if (arrayItem == null) {
                continue;
            }

            ident(buf, level);
            buf.append('<');
            buf.append(indexProp.getName());
            buf.append('>');
            if (rendererMetaOptions.getRenderer() == null) {
                indexProp.getOutput().render(arrayItem, buf);
            } else {
                EventPropertyRendererContext context = rendererMetaOptions.getRendererContext();
                context.setStringBuilderAndReset(buf);
                context.setPropertyName(indexProp.getName());
                context.setPropertyValue(arrayItem);
                context.setIndexedPropertyIndex(i);
                context.setDefaultRenderer(indexProp.getOutput());
                rendererMetaOptions.getRenderer().render(context);
            }
            buf.append("</");
            buf.append(indexProp.getName());
            buf.append('>');
            buf.append(NEWLINE);
        }
    }

    GetterPair[] mappedProps = meta.getMappedProperties();
    for (GetterPair mappedProp : mappedProps) {
        Object value = mappedProp.getGetter().get(theEvent);

        if ((value != null) && (!(value instanceof Map))) {
            log.warn("Property '" + mappedProp.getName() + "' expected to return Map and returned "
                    + value.getClass() + " instead");
            continue;
        }

        ident(buf, level);
        buf.append('<');
        buf.append(mappedProp.getName());

        if (value != null) {
            Map<String, Object> map = (Map<String, Object>) value;
            if (!map.isEmpty()) {
                Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
                for (; it.hasNext();) {
                    Map.Entry<String, Object> entry = it.next();
                    if ((entry.getKey() == null) || (entry.getValue() == null)) {
                        continue;
                    }

                    buf.append(" ");
                    buf.append(entry.getKey());
                    buf.append("=\"");
                    OutputValueRenderer outputValueRenderer = new OutputValueRendererXMLString();

                    if (rendererMetaOptions.getRenderer() == null) {
                        outputValueRenderer.render(entry.getValue(), buf);
                    } else {
                        EventPropertyRendererContext context = rendererMetaOptions.getRendererContext();
                        context.setStringBuilderAndReset(buf);
                        context.setPropertyName(mappedProp.getName());
                        context.setPropertyValue(entry.getValue());
                        context.setMappedPropertyKey(entry.getKey());
                        context.setDefaultRenderer(outputValueRenderer);
                        rendererMetaOptions.getRenderer().render(context);
                    }

                    buf.append("\"");
                }
            }
        }

        buf.append("/>");
        buf.append(NEWLINE);
    }

    NestedGetterPair[] nestedProps = meta.getNestedProperties();
    for (NestedGetterPair nestedProp : nestedProps) {
        Object value = nestedProp.getGetter().getFragment(theEvent);

        if (value == null) {
            continue;
        }

        if (!nestedProp.isArray()) {
            if (!(value instanceof EventBean)) {
                log.warn("Property '" + nestedProp.getName() + "' expected to return EventBean and returned "
                        + value.getClass() + " instead");
                buf.append("null");
                continue;
            }
            EventBean nestedEventBean = (EventBean) value;
            renderAttInner(buf, level, nestedEventBean, nestedProp);
        } else {
            if (!(value instanceof EventBean[])) {
                log.warn("Property '" + nestedProp.getName() + "' expected to return EventBean[] and returned "
                        + value.getClass() + " instead");
                buf.append("null");
                continue;
            }

            EventBean[] nestedEventArray = (EventBean[]) value;
            for (int i = 0; i < nestedEventArray.length; i++) {
                EventBean arrayItem = nestedEventArray[i];
                renderAttInner(buf, level, arrayItem, nestedProp);
            }
        }
    }

    return buf.toString();
}

From source file:Main.java

/**
 * convert value to given type.//from  w ww .  j a  v  a 2s .  co  m
 * null safe.
 *
 * @param value value for convert
 * @param type  will converted type
 * @return value while converted
 */
public static Object convertCompatibleType(Object value, Class<?> type) {

    if (value == null || type == null || type.isAssignableFrom(value.getClass())) {
        return value;
    }
    if (value instanceof String) {
        String string = (String) value;
        if (char.class.equals(type) || Character.class.equals(type)) {
            if (string.length() != 1) {
                throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!"
                        + " when convert String to char, the String MUST only 1 char.", string));
            }
            return string.charAt(0);
        } else if (type.isEnum()) {
            return Enum.valueOf((Class<Enum>) type, string);
        } else if (type == BigInteger.class) {
            return new BigInteger(string);
        } else if (type == BigDecimal.class) {
            return new BigDecimal(string);
        } else if (type == Short.class || type == short.class) {
            return Short.valueOf(string);
        } else if (type == Integer.class || type == int.class) {
            return Integer.valueOf(string);
        } else if (type == Long.class || type == long.class) {
            return Long.valueOf(string);
        } else if (type == Double.class || type == double.class) {
            return Double.valueOf(string);
        } else if (type == Float.class || type == float.class) {
            return Float.valueOf(string);
        } else if (type == Byte.class || type == byte.class) {
            return Byte.valueOf(string);
        } else if (type == Boolean.class || type == boolean.class) {
            return Boolean.valueOf(string);
        } else if (type == Date.class) {
            try {
                return new SimpleDateFormat(DATE_FORMAT).parse((String) value);
            } catch (ParseException e) {
                throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT
                        + ", cause: " + e.getMessage(), e);
            }
        } else if (type == Class.class) {
            return forName((String) value);
        }
    } else if (value instanceof Number) {
        Number number = (Number) value;
        if (type == byte.class || type == Byte.class) {
            return number.byteValue();
        } else if (type == short.class || type == Short.class) {
            return number.shortValue();
        } else if (type == int.class || type == Integer.class) {
            return number.intValue();
        } else if (type == long.class || type == Long.class) {
            return number.longValue();
        } else if (type == float.class || type == Float.class) {
            return number.floatValue();
        } else if (type == double.class || type == Double.class) {
            return number.doubleValue();
        } else if (type == BigInteger.class) {
            return BigInteger.valueOf(number.longValue());
        } else if (type == BigDecimal.class) {
            return BigDecimal.valueOf(number.doubleValue());
        } else if (type == Date.class) {
            return new Date(number.longValue());
        }
    } else if (value instanceof Collection) {
        Collection collection = (Collection) value;
        if (type.isArray()) {
            int length = collection.size();
            Object array = Array.newInstance(type.getComponentType(), length);
            int i = 0;
            for (Object item : collection) {
                Array.set(array, i++, item);
            }
            return array;
        } else if (!type.isInterface()) {
            try {
                Collection result = (Collection) type.newInstance();
                result.addAll(collection);
                return result;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        } else if (type == List.class) {
            return new ArrayList<>(collection);
        } else if (type == Set.class) {
            return new HashSet<>(collection);
        }
    } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) {
        Collection collection;
        if (!type.isInterface()) {
            try {
                collection = (Collection) type.newInstance();
            } catch (Throwable e) {
                collection = new ArrayList<>();
            }
        } else if (type == Set.class) {
            collection = new HashSet<>();
        } else {
            collection = new ArrayList<>();
        }
        int length = Array.getLength(value);
        for (int i = 0; i < length; i++) {
            collection.add(Array.get(value, i));
        }
        return collection;
    }
    return value;
}

From source file:org.paxml.control.IterateTag.java

private ChildrenResultList visitArray(Context context, Object array) {
    if (array == null) {
        return null;
    }//from  w ww .  ja v  a2  s .c  om
    ChildrenResultList list = null;
    final int len = Array.getLength(array);
    for (int i = 0; i < len; i++) {
        Object value = Array.get(array, i);
        list = addAll(list, visit(context, array, i + "", i, value));

    }
    return list;
}

From source file:com.espertech.esper.event.util.XMLRendererImpl.java

private String renderAttElements(EventBean theEvent, int level, RendererMeta meta) {
    StringBuilder buf = new StringBuilder();

    GetterPair[] indexProps = meta.getIndexProperties();
    for (GetterPair indexProp : indexProps) {
        Object value = indexProp.getGetter().get(theEvent);

        if (value == null) {
            continue;
        }//from w w w.j a v a2  s .  c o m
        if (!value.getClass().isArray()) {
            log.warn("Property '" + indexProp.getName() + "' returned a non-array object");
            continue;
        }
        for (int i = 0; i < Array.getLength(value); i++) {
            Object arrayItem = Array.get(value, i);

            if (arrayItem == null) {
                continue;
            }

            ident(buf, level);
            buf.append('<');
            buf.append(indexProp.getName());
            buf.append('>');
            if (rendererMetaOptions.getRenderer() == null) {
                indexProp.getOutput().render(arrayItem, buf);
            } else {
                EventPropertyRendererContext context = rendererMetaOptions.getRendererContext();
                context.setStringBuilderAndReset(buf);
                context.setPropertyName(indexProp.getName());
                context.setPropertyValue(arrayItem);
                context.setIndexedPropertyIndex(i);
                context.setDefaultRenderer(indexProp.getOutput());
                rendererMetaOptions.getRenderer().render(context);
            }
            buf.append("</");
            buf.append(indexProp.getName());
            buf.append('>');
            buf.append(NEWLINE);
        }
    }

    GetterPair[] mappedProps = meta.getMappedProperties();
    for (GetterPair mappedProp : mappedProps) {
        Object value = mappedProp.getGetter().get(theEvent);

        if ((value != null) && (!(value instanceof Map))) {
            log.warn("Property '" + mappedProp.getName() + "' expected to return Map and returned "
                    + value.getClass() + " instead");
            continue;
        }

        ident(buf, level);
        buf.append('<');
        buf.append(mappedProp.getName());

        if (value != null) {
            Map<String, Object> map = (Map<String, Object>) value;
            if (!map.isEmpty()) {
                Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
                for (; it.hasNext();) {
                    Map.Entry<String, Object> entry = it.next();
                    if ((entry.getKey() == null) || (entry.getValue() == null)) {
                        continue;
                    }

                    buf.append(" ");
                    buf.append(entry.getKey());
                    buf.append("=\"");
                    OutputValueRenderer outputValueRenderer = OutputValueRendererFactory
                            .getOutputValueRenderer(entry.getValue().getClass(), rendererMetaOptions);

                    if (rendererMetaOptions.getRenderer() == null) {
                        outputValueRenderer.render(entry.getValue(), buf);
                    } else {
                        EventPropertyRendererContext context = rendererMetaOptions.getRendererContext();
                        context.setStringBuilderAndReset(buf);
                        context.setPropertyName(mappedProp.getName());
                        context.setPropertyValue(entry.getValue());
                        context.setMappedPropertyKey(entry.getKey());
                        context.setDefaultRenderer(outputValueRenderer);
                        rendererMetaOptions.getRenderer().render(context);
                    }

                    buf.append("\"");
                }
            }
        }

        buf.append("/>");
        buf.append(NEWLINE);
    }

    NestedGetterPair[] nestedProps = meta.getNestedProperties();
    for (NestedGetterPair nestedProp : nestedProps) {
        Object value = nestedProp.getGetter().getFragment(theEvent);

        if (value == null) {
            continue;
        }

        if (!nestedProp.isArray()) {
            if (!(value instanceof EventBean)) {
                log.warn("Property '" + nestedProp.getName() + "' expected to return EventBean and returned "
                        + value.getClass() + " instead");
                buf.append("null");
                continue;
            }
            EventBean nestedEventBean = (EventBean) value;
            renderAttInner(buf, level, nestedEventBean, nestedProp);
        } else {
            if (!(value instanceof EventBean[])) {
                log.warn("Property '" + nestedProp.getName() + "' expected to return EventBean[] and returned "
                        + value.getClass() + " instead");
                buf.append("null");
                continue;
            }

            EventBean[] nestedEventArray = (EventBean[]) value;
            for (int i = 0; i < nestedEventArray.length; i++) {
                EventBean arrayItem = nestedEventArray[i];
                renderAttInner(buf, level, arrayItem, nestedProp);
            }
        }
    }

    return buf.toString();
}

From source file:io.s4.comm.util.JSONUtil.java

public static Map<String, Object> getMap(Object obj) {
    Map<String, Object> map = new HashMap<String, Object>();
    if (obj != null) {
        if (Map.class.isAssignableFrom(obj.getClass())) {
            return (Map) obj;
        } else {/*from  w  ww.  j  av  a  2 s  .  c  o  m*/

            Field[] fields = obj.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                if (!fields[i].isAccessible()) {
                    fields[i].setAccessible(true);
                }
                try {
                    String name = fields[i].getName();
                    Object val = fields[i].get(obj);
                    if (!Modifier.isStatic(fields[i].getModifiers())
                            && !Modifier.isTransient(fields[i].getModifiers())) {
                        if (fields[i].getType().isPrimitive() || knownTypes.contains(fields[i].getType())) {
                            map.put(name, val);
                        } else if (fields[i].getType().isArray()) {
                            int length = Array.getLength(val);
                            Object vals[] = new Object[length];
                            for (int j = 0; j < length; j++) {
                                Object arrVal = Array.get(val, j);
                                if (arrVal.getClass().isPrimitive() || knownTypes.contains(arrVal.getClass())) {
                                    vals[j] = arrVal;
                                } else {
                                    vals[j] = getMap(arrVal);
                                }
                            }
                            map.put(name, vals);
                        } else {
                            map.put(name, getMap(val));
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException("Exception while getting value of " + fields[i], e);
                }
            }
        }
    }
    return map;
}

From source file:org.apereo.portal.utils.cache.PersonDirectoryCacheKeyGenerator.java

@Override
public Serializable generateKey(MethodInvocation methodInvocation) {
    //Determine the targeted CachableMethod
    final CachableMethod cachableMethod = this.resolvedMethodCache.getUnchecked(methodInvocation.getMethod());

    //Use the resolved cachableMethod to determine the seed Map and then get the hash of the key elements
    final Object[] methodArguments = methodInvocation.getArguments();

    final CacheKey.CacheKeyBuilder<String, Serializable> cacheKeyBuilder = CacheKey
            .builder(cachableMethod.getName());

    switch (cachableMethod) {
    //Both methods that take a Map argument can just have the first argument returned
    case PEOPLE_MAP:
    case PEOPLE_MULTIVALUED_MAP:
    case MULTIVALUED_USER_ATTRIBUTES__MAP:
    case USER_ATTRIBUTES__MAP: {
        final Map<String, Object> queryMap = (Map<String, Object>) methodArguments[0];

        //If possible tag the cache key with the username
        final String usernameAttribute = this.usernameAttributeProvider.getUsernameAttribute();
        Object usernameValue = queryMap.get(usernameAttribute);
        if (usernameValue instanceof String) {
            cacheKeyBuilder.addTag(UsernameTaggedCacheEntryPurger.createCacheEntryTag((String) usernameValue));
        } else if (usernameValue instanceof List) {
            final List usernameValueList = (List) usernameValue;
            if (usernameValueList.size() == 1) {
                usernameValue = usernameValueList.get(0);
                if (usernameValue instanceof String) {
                    cacheKeyBuilder/* w ww. j  ava 2  s  . com*/
                            .addTag(UsernameTaggedCacheEntryPurger.createCacheEntryTag((String) usernameValue));
                }
            }
        }

        for (final Map.Entry<String, Object> e : queryMap.entrySet()) {
            final String key = e.getKey();
            final Object value = e.getValue();

            //Skip null/empty attribute values
            if (ignoreEmptyAttributes
                    && (value == null || (value instanceof Collection && ((Collection) value).isEmpty())
                            || (value instanceof Map && ((Map) value).isEmpty())
                            || (value.getClass().isArray() && Array.getLength(value) == 0))) {
                continue;
            }

            if (value == null || value instanceof Serializable) {
                cacheKeyBuilder.put(key, (Serializable) value);
            } else {
                cacheKeyBuilder.put(key, value.getClass());
            }
        }
        break;
    }

    //The multivalued attributes with a string needs to be converted to Map<String, List<Object>>
    case MULTIVALUED_USER_ATTRIBUTES__STR: {
        final String uid = (String) methodArguments[0];
        if (StringUtils.isEmpty(uid)) {
            break;
        }

        cacheKeyBuilder.add(uid);
        cacheKeyBuilder.addTag(UsernameTaggedCacheEntryPurger.createCacheEntryTag(uid));
        break;
    }

    //The single valued attributes with a string needs to be converted to Map<String, Object>
    case PERSON_STR:
    case USER_ATTRIBUTES__STR: {
        final String uid = (String) methodArguments[0];
        if (StringUtils.isEmpty(uid)) {
            break;
        }
        cacheKeyBuilder.add(uid);
        cacheKeyBuilder.addTag(UsernameTaggedCacheEntryPurger.createCacheEntryTag(uid));
        break;
    }

    case POSSIBLE_USER_ATTRIBUTE_NAMES:
    case AVAILABLE_QUERY_ATTRIBUTES: {
        break;
    }

    default: {
        throw new IllegalArgumentException("Unsupported CachableMethod resolved: '" + cachableMethod + "'");
    }
    }

    if (cacheKeyBuilder.size() == 0) {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("No cache key generated for MethodInvocation='" + methodInvocation + "'");
        }

        return null;
    }

    final CacheKey cacheKey = cacheKeyBuilder.build();
    if (this.logger.isDebugEnabled()) {
        this.logger.debug(
                "Generated cache key '" + cacheKey + "' for MethodInvocation='" + methodInvocation + "'");
    }
    return cacheKey;
}

From source file:com.discovery.darchrow.lang.ArrayUtil.java

/**
 * ?? {@link java.util.Iterator}./*w w  w. jav  a  2s .  c  o 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 if (null == arrays) return 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()
 */
@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) {
        if (LOGGER.isDebugEnabled()) {
            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:com.laidians.utils.ObjectUtils.java

/**
 * ??object//from   ww w  .jav a 2  s. c om
 * @param source
 * @return
 */
public static Object[] toObjectArray(Object source) {
    //
    if (source instanceof Object[]) {
        return (Object[]) source;
    }
    //
    if (source == null) {
        return new Object[0];
    }
    //?
    if (!source.getClass().isArray()) {
        throw new IllegalArgumentException("Source is not an array: " + source);
    }
    //
    int length = Array.getLength(source);
    if (length == 0) {
        return new Object[0];
    }
    //?
    Class wrapperType = Array.get(source, 0).getClass();
    //?
    Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
    for (int i = 0; i < length; i++) {
        newArray[i] = Array.get(source, i);
    }
    return newArray;
}