Example usage for java.lang.reflect Array get

List of usage examples for java.lang.reflect Array get

Introduction

In this page you can find the example usage for java.lang.reflect Array get.

Prototype

public static native Object get(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

Source Link

Document

Returns the value of the indexed component in the specified array object.

Usage

From source file:cat.albirar.framework.dynabean.impl.DynaBeanImpl.java

/**
 * Clone or copy a property value./*from www . j a  v a 2 s. co  m*/
 * Only applicable on clone call.
 * <ul>
 * <li>If {@code originalValue} is {@link Cloneable}, makes a clone.</li>
 * <li>If {@code originalValue} IS NOT {@link Cloneable}, search for an {@link PropertyEditor editor} and copy.</li>
 * <li>If cannot found a properly {@link PropertyEditor editor}, simply return the {@code originalValue}</li>
 * </ul>
 * @param propDesc The property descriptor
 * @param originalValue The value to clone
 * @return The cloned value
 */
private Object cloneValue(DynaBeanPropertyDescriptor propDesc, Object originalValue) {
    Iterator<?> iterator;
    int n;
    IPropertyWriter writer;
    ITransformerVisitor<Object> reader;

    // only null?
    if (originalValue == null) {
        return null;
    }

    if (propDesc.isItemDynaBean()) {
        reader = new ObjectCopyReaderVisitor(descriptor.getFactory());
    } else {
        if (propDesc.getPropertyItemCloneMethod() != null) {
            reader = new ObjectCopyReaderVisitor(propDesc.getPropertyItemCloneMethod());
        } else {
            if (propDesc.getPropertyItemEditor() != null) {
                reader = new ObjectCopyReaderVisitor(propDesc.getPropertyItemEditor());
            } else {
                reader = new ObjectCopyReaderVisitor();
            }
        }
    }
    writer = prepareWriter(propDesc, reader);
    if (propDesc.isArray()) {
        for (n = 0; n < Array.getLength(originalValue); n++) {
            writer.visit(Array.get(originalValue, n));
        }
    } else {
        if (propDesc.isCollection()) {
            iterator = ((Collection<?>) originalValue).iterator();
            while (iterator.hasNext()) {
                writer.visit(iterator.next());
            }
        } else {
            writer.visit(originalValue);
        }
    }
    return writer.getReturnValue();
}

From source file:org.moeaframework.core.PRNGTest.java

/**
 * Tests if the {@code shuffle} method produces valid permutations of a
 * typed array, and that the distribution of the values for each index are
 * approximately uniform.// w w  w .ja  va 2  s .  c  o m
 * 
 * @param type the class of the array
 * @param size the size of the array
 */
public void testShuffleArray(Class<?> type, int size) throws Exception {
    Object array = Array.newInstance(type.getComponentType(), size);
    DescriptiveStatistics[] statistics = new DescriptiveStatistics[size];

    for (int i = 0; i < size; i++) {
        // casts are needed when truncating the int
        if (type.getComponentType() == short.class) {
            Array.set(array, i, (short) i);
        } else if (type.getComponentType() == byte.class) {
            Array.set(array, i, (byte) i);
        } else {
            Array.set(array, i, i);
        }

        statistics[i] = new DescriptiveStatistics();
    }

    for (int i = 0; i < 50000; i++) {
        Method method = PRNG.class.getMethod("shuffle", type);
        method.invoke(null, array);

        Integer[] integerArray = new Integer[size];

        for (int j = 0; j < size; j++) {
            int value = ((Number) Array.get(array, j)).intValue();
            integerArray[j] = value;
            statistics[j].addValue(value);
        }

        testPermutation(size, integerArray);
    }

    for (int i = 0; i < size; i++) {
        testUniformDistribution(0, size - 1, statistics[i]);
    }
}

From source file:org.jaffa.util.BeanHelper.java

/** Clones the input bean, performing a deep copy of its properties.
 * @param bean the bean to be cloned.// ww  w . j a  v a2s .  c om
 * @param deepCloneForeignField if false, then the foreign-fields of a GraphDataObject will not be deep cloned.
 * @return a clone of the input bean.
 * @throws IllegalAccessException if the underlying method is inaccessible.
 * @throws InvocationTargetException if the underlying method throws an exception.
 * @throws InstantiationException if the bean cannot be instantiated.
 * @throws IntrospectionException if an exception occurs during introspection.
 */
public static Object cloneBean(Object bean, boolean deepCloneForeignField) throws IllegalAccessException,
        InvocationTargetException, InstantiationException, IntrospectionException {
    if (bean == null)
        return bean;

    Class beanClass = bean.getClass();

    // Return the input as-is, if immutable
    if (beanClass == String.class || beanClass == Boolean.class || Number.class.isAssignableFrom(beanClass)
            || IDateBase.class.isAssignableFrom(beanClass) || Currency.class.isAssignableFrom(beanClass)
            || beanClass.isPrimitive()) {
        return bean;
    }

    // Handle an array
    if (beanClass.isArray()) {
        Class componentType = beanClass.getComponentType();
        int length = Array.getLength(bean);
        Object clone = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Object arrayElementClone = cloneBean(Array.get(bean, i), deepCloneForeignField);
            Array.set(clone, i, arrayElementClone);
        }
        return clone;
    }

    // Handle a Collection
    if (bean instanceof Collection) {
        Collection clone = (Collection) bean.getClass().newInstance();
        for (Object collectionElement : (Collection) bean) {
            Object collectionElementClone = cloneBean(collectionElement, deepCloneForeignField);
            clone.add(collectionElementClone);
        }
        return clone;
    }

    // Handle a Map
    if (bean instanceof Map) {
        Map clone = (Map) bean.getClass().newInstance();
        for (Iterator i = ((Map) bean).entrySet().iterator(); i.hasNext();) {
            Map.Entry me = (Map.Entry) i.next();
            Object keyClone = cloneBean(me.getKey(), deepCloneForeignField);
            Object valueClone = cloneBean(me.getValue(), deepCloneForeignField);
            clone.put(keyClone, valueClone);
        }
        return clone;
    }

    // Invoke the 'public Object clone()' method, if available
    if (bean instanceof Cloneable) {
        try {
            Method cloneMethod = beanClass.getMethod("clone");
            return cloneMethod.invoke(bean);
        } catch (NoSuchMethodException e) {
            // do nothing
        }
    }

    // Create a clone using bean introspection
    Object clone = beanClass.newInstance();
    BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    if (beanInfo != null) {
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        if (pds != null) {
            // Obtain a GraphMapping; only if foreign-fields are not to be cloned
            //Use reflection to achieve the following:
            //GraphMapping graphMapping = !deepCloneForeignField && bean instanceof GraphDataObject ? MappingFactory.getInstance(bean) : null;
            Object graphMapping = null;
            Method isForeignFieldMethod = null;
            try {
                if (!deepCloneForeignField
                        && Class.forName("org.jaffa.soa.graph.GraphDataObject").isInstance(bean)) {
                    graphMapping = Class.forName("org.jaffa.soa.dataaccess.MappingFactory")
                            .getMethod("getInstance", Object.class).invoke(null, bean);
                    isForeignFieldMethod = graphMapping.getClass().getMethod("isForeignField", String.class);
                }
            } catch (Exception e) {
                // do nothing since JaffaSOA may not be deployed
                if (log.isDebugEnabled())
                    log.debug("Exception in obtaining the GraphMapping", e);
            }

            for (PropertyDescriptor pd : pds) {
                if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
                    // Do not clone a foreign-field
                    Object property = pd.getReadMethod().invoke(bean);

                    //Use reflection to achieve the following:
                    //Object propertyClone = graphMapping != null && graphMapping.isForeignField(pd.getName()) ? property : cloneBean(property, deepCloneForeignField);
                    Object propertyClone = null;
                    boolean propertyCloned = false;
                    if (graphMapping != null && isForeignFieldMethod != null) {
                        try {
                            if ((Boolean) isForeignFieldMethod.invoke(graphMapping, pd.getName())) {
                                propertyClone = property;
                                propertyCloned = true;
                            }
                        } catch (Exception e) {
                            // do nothing since JaffaSOA may not be deployed
                            if (log.isDebugEnabled())
                                log.debug("Exception in invoking GraphMapping.isForeignField()", e);
                        }
                    }
                    if (!propertyCloned)
                        propertyClone = cloneBean(property, deepCloneForeignField);

                    pd.getWriteMethod().invoke(clone, propertyClone);
                }
            }
        }
    }
    return clone;
}

From source file:javadz.beanutils.LazyDynaBean.java

/**
 * <p>Return the value of an indexed property with the specified name.</p>
 *
 * <p><strong>N.B.</strong> Returns <code>null</code> if there is no 'indexed'
 * property of the specified name.</p>
 *
 * @param name Name of the property whose value is to be retrieved
 * @param index Index of the value to be retrieved
 * @return The indexed property's value/*from  ww  w  . j  a v  a  2  s  .c  o  m*/
 *
 * @exception IllegalArgumentException if the specified property
 *  exists, but is not indexed
 * @exception IndexOutOfBoundsException if the specified index
 *  is outside the range of the underlying property
 */
public Object get(String name, int index) {

    // If its not a property, then create default indexed property
    if (!isDynaProperty(name)) {
        set(name, defaultIndexedProperty(name));
    }

    // Get the indexed property
    Object indexedProperty = get(name);

    // Check that the property is indexed
    if (!dynaClass.getDynaProperty(name).isIndexed()) {
        throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]' "
                + dynaClass.getDynaProperty(name).getName());
    }

    // Grow indexed property to appropriate size
    indexedProperty = growIndexedProperty(name, indexedProperty, index);

    // Return the indexed value
    if (indexedProperty.getClass().isArray()) {
        return Array.get(indexedProperty, index);
    } else if (indexedProperty instanceof List) {
        return ((List) indexedProperty).get(index);
    } else {
        throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]' "
                + indexedProperty.getClass().getName());
    }

}

From source file:org.enerj.apache.commons.beanutils.ConvertUtilsBean.java

/**
 * Convert the specified value into a String.  If the specified value
 * is an array, the first element (converted to a String) will be
 * returned.  The registered {@link Converter} for the
 * <code>java.lang.String</code> class will be used, which allows
 * applications to customize Object->String conversions (the default
 * implementation simply uses toString()).
 *
 * @param value Value to be converted (may be null)
 *//*from  ww  w  .j  a  v a 2s  .co  m*/
public String convert(Object value) {

    if (value == null) {
        return ((String) null);
    } else if (value.getClass().isArray()) {
        if (Array.getLength(value) < 1) {
            return (null);
        }
        value = Array.get(value, 0);
        if (value == null) {
            return ((String) null);
        } else {
            Converter converter = lookup(String.class);
            return ((String) converter.convert(String.class, value));
        }
    } else {
        Converter converter = lookup(String.class);
        return ((String) converter.convert(String.class, value));
    }

}

From source file:org.datanucleus.store.scalaris.fieldmanager.StoreFieldManager.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected void storeObjectFieldInternal(int fieldNumber, Object value, AbstractMemberMetaData mmd,
        ClassLoaderResolver clr) throws JSONException {
    RelationType relationType = mmd.getRelationType(clr);
    String name = storeMgr.getNamingFactory().getColumnName(mmd, ColumnType.COLUMN);

    if (value == null) {
        jsonobj.put(name, JSONObject.NULL);
        return;/*www .  j a  va2 s.  c o m*/
    } else if (relationType == RelationType.NONE) {
        if (mmd.getTypeConverterName() != null) {
            // User-defined converter
            TypeConverter conv = op.getExecutionContext().getTypeManager()
                    .getTypeConverterForName(mmd.getTypeConverterName());
            jsonobj.put(name, conv.toDatastoreType(value));
            return;
        } else if (value instanceof Boolean) {
            jsonobj.put(name, ((Boolean) value).booleanValue());
        } else if (value instanceof Integer) {
            jsonobj.put(name, ((Integer) value).intValue());
        } else if (value instanceof Long) {
            jsonobj.put(name, ((Long) value).longValue());
        } else if (value instanceof Double) {
            jsonobj.put(name, ((Double) value).doubleValue());
        } else if (value instanceof Date) {
            Date dateValue = (Date) value;
            jsonobj.put(name, dateValue.getTime());
        } else if (value instanceof Enum) {
            jsonobj.put(name, ((Enum) value).ordinal());
        } else if (value instanceof BigDecimal) {
            jsonobj.put(name, value);
        } else if (value instanceof BigInteger) {
            jsonobj.put(name, value);
        } else if (value instanceof Collection) {
            // Collection<Non-PC> will be returned as JSONArray
            jsonobj.put(name, value);
        } else if (value instanceof Map) {
            jsonobj.put(name, value);
        } else {
            // See if we can persist it as a Long/String
            boolean useLong = false;
            ColumnMetaData[] colmds = mmd.getColumnMetaData();
            if (colmds != null && colmds.length == 1) {
                JdbcType jdbcType = colmds[0].getJdbcType();
                if (jdbcType != null) {
                    String jdbc = jdbcType.name();
                    if (jdbc != null
                            && (jdbc.equalsIgnoreCase("INTEGER") || jdbc.equalsIgnoreCase("NUMERIC"))) {
                        useLong = true;
                    }
                }
            }
            TypeConverter strConv = op.getExecutionContext().getNucleusContext().getTypeManager()
                    .getTypeConverterForType(mmd.getType(), String.class);
            TypeConverter longConv = op.getExecutionContext().getNucleusContext().getTypeManager()
                    .getTypeConverterForType(mmd.getType(), Long.class);
            if (useLong) {
                if (longConv != null) {
                    jsonobj.put(name, longConv.toDatastoreType(value));
                    return;
                }
            } else {
                if (strConv != null) {
                    jsonobj.put(name, strConv.toDatastoreType(value));
                    return;
                } else if (longConv != null) {
                    jsonobj.put(name, longConv.toDatastoreType(value));
                    return;
                }
            }

            // Fallback to persist as a JSONObject and see what happens
            JSONObject jsonobjfield = new JSONObject(value);
            jsonobjfield.put("class", value.getClass().getName());
            jsonobj.put(name, jsonobjfield);
        }

        return;
    } else if (RelationType.isRelationSingleValued(relationType)) {
        // 1-1, N-1 relation, so store the "id"
        final Object valuePC = op.getExecutionContext().persistObjectInternal(value, op, fieldNumber, -1);
        final Object valueId = op.getExecutionContext().getApiAdapter().getIdForObject(valuePC);
        if (valueId != null) {
            jsonobj.put(name, IdentityUtils.getPersistableIdentityForId(valueId));

            ObjectProvider<?> intern = ec.findObjectProvider(valuePC);
            if (intern.getLifecycleState().stateType() == LifeCycleState.P_NEW) {
                // Loaded flags must be cleared for the internal object in case
                // it was only persisted indirectly via PersistenceManager.
                // This prevents registering updates on the objects if it is
                // not fetched once before.
                intern.clearLoadedFlags();
            }
        }
        return;
    } else if (RelationType.isRelationMultiValued(relationType)) {
        // Collection/Map/Array
        if (mmd.hasCollection()) {
            final Collection<String> idColl = new ArrayList<String>();
            final Collection<?> coll = (Collection<?>) value;
            final Iterator<?> collIter = coll.iterator();
            while (collIter.hasNext()) {
                final Object element = collIter.next();
                final Object elementPC = op.getExecutionContext().persistObjectInternal(element, op,
                        fieldNumber, -1);
                final Object elementID = op.getExecutionContext().getApiAdapter().getIdForObject(elementPC);

                String objId = IdentityUtils.getPersistableIdentityForId(elementID);
                if (objId != null) {
                    // object with this ID was already deleted
                    idColl.add(objId);
                }
            }

            jsonobj.put(name, idColl);
            return;
        } else if (mmd.hasArray()) {
            Collection ids = new ArrayList(Array.getLength(value));
            for (int i = 0; i < Array.getLength(value); i++) {
                final Object element = Array.get(value, i);
                final Object elementPC = op.getExecutionContext().persistObjectInternal(element, op,
                        fieldNumber, -1);
                final Object elementID = op.getExecutionContext().getApiAdapter().getIdForObject(elementPC);

                String objId = IdentityUtils.getPersistableIdentityForId(elementID);
                if (objId != null) {
                    // object with this ID was already deleted
                    ids.add(objId);
                }
            }
            jsonobj.put(name, ids);
            return;
        } else if (mmd.hasMap()) {
            AbstractClassMetaData keyCmd = mmd.getMap().getKeyClassMetaData(clr,
                    op.getExecutionContext().getMetaDataManager());
            AbstractClassMetaData valCmd = mmd.getMap().getValueClassMetaData(clr,
                    op.getExecutionContext().getMetaDataManager());

            Map idMap = new HashMap();
            Map map = (Map) value;
            Iterator<Map.Entry> mapIter = map.entrySet().iterator();
            while (mapIter.hasNext()) {
                Map.Entry entry = mapIter.next();
                Object key = null;
                Object val = null;
                if (keyCmd != null) {
                    Object keyPC = op.getExecutionContext().persistObjectInternal(entry.getKey(), op,
                            fieldNumber, -1);
                    key = op.getExecutionContext().getApiAdapter().getIdForObject(keyPC);
                } else {
                    key = entry.getKey();
                }
                if (valCmd != null) {
                    Object valPC = op.getExecutionContext().persistObjectInternal(entry.getValue(), op,
                            fieldNumber, -1);
                    val = op.getExecutionContext().getApiAdapter().getIdForObject(valPC);
                } else {
                    val = entry.getValue();
                }
                idMap.put(key, val);
            }
            jsonobj.put(name, idMap);
            return;
        }
    }

    throw new NucleusException(
            "Dont currently support field " + mmd.getFullFieldName() + " of type " + mmd.getTypeName());
}

From source file:com.android.camera2.its.ItsSerializer.java

@SuppressWarnings("unchecked")
private static MetadataEntry serializeArrayEntry(Type keyType, Object keyObj, CameraMetadata md)
        throws ItsException {
    String keyName = getKeyName(keyObj);
    try {/*from ww w  .  ja  va2  s  . com*/
        Object keyValue = getKeyValue(md, keyObj);
        if (keyValue == null) {
            return new MetadataEntry(keyName, JSONObject.NULL);
        }
        int arrayLen = Array.getLength(keyValue);
        Type elmtType = ((GenericArrayType) keyType).getGenericComponentType();
        if (elmtType == int.class || elmtType == float.class || elmtType == byte.class || elmtType == long.class
                || elmtType == double.class || elmtType == boolean.class) {
            return new MetadataEntry(keyName, new JSONArray(keyValue));
        } else if (elmtType == Rational.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeRational((Rational) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == Size.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeSize((Size) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == Rect.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeRect((Rect) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == Face.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeFace((Face) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == StreamConfigurationMap.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeStreamConfigurationMap((StreamConfigurationMap) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType instanceof ParameterizedType
                && ((ParameterizedType) elmtType).getRawType() == Range.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeRange((Range) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType instanceof ParameterizedType
                && ((ParameterizedType) elmtType).getRawType() == Pair.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializePair((Pair) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == MeteringRectangle.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeMeteringRectangle((MeteringRectangle) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == Location.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeLocation((Location) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == RggbChannelVector.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeRggbChannelVector((RggbChannelVector) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == BlackLevelPattern.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializeBlackLevelPattern((BlackLevelPattern) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else if (elmtType == Point.class) {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < arrayLen; i++) {
                jsonArray.put(serializePoint((Point) Array.get(keyValue, i)));
            }
            return new MetadataEntry(keyName, jsonArray);
        } else {
            Logt.w(TAG, String.format("Serializing unsupported array type: " + elmtType));
            return null;
        }
    } catch (org.json.JSONException e) {
        throw new ItsException("JSON error for key: " + keyName + ": ", e);
    }
}

From source file:com.googlecode.jsonplugin.JSONWriter.java

/**
 * Add array to buffer/*from   w  w w.  ja v  a2 s  .co m*/
 */
private void array(Object object, Method method) throws JSONException {
    this.add("[");

    int length = Array.getLength(object);

    boolean hasData = false;
    for (int i = 0; i < length; ++i) {
        String expr = null;
        if (this.buildExpr) {
            expr = this.expandExpr(i);
            if (this.shouldExcludeProperty(expr)) {
                continue;
            }
            expr = this.setExprStack(expr);
        }
        if (hasData) {
            this.add(',');
        }
        hasData = true;
        this.value(Array.get(object, i), method);
        if (this.buildExpr) {
            this.setExprStack(expr);
        }
    }

    this.add("]");
}

From source file:com.astamuse.asta4d.web.form.flow.base.BasicFormFlowSnippetTrait.java

/**
 * Sub classes could override this method to customize how to handle the injection trace data for type unmatch errors.
 * /*from www  .j a  va 2  s  . co  m*/
 * @param fieldName
 * @param fieldDataType
 * @param rawTraceData
 * @return
 */
default Object convertRawInjectionTraceDataToRenderingData(String fieldName, Class<?> fieldDataType,
        Object rawTraceData) {
    if (fieldDataType.isArray() && rawTraceData.getClass().isArray()) {
        return rawTraceData;
    } else if (rawTraceData.getClass().isArray()) {// but field data type is
                                                   // not array
        if (Array.getLength(rawTraceData) > 0) {
            return Array.get(rawTraceData, 0);
        } else {
            return null;
        }
    } else {
        return rawTraceData;
    }
}

From source file:ome.services.util.ServiceHandler.java

/**
 * public for testing purposes./*from   w w  w .  j a v a  2s  .c  o  m*/
 */
public String getResultsString(Object o, IdentityHashMap<Object, String> cache) {

    if (o == null) {
        return "null";
    }

    if (cache == null) {
        cache = new IdentityHashMap<Object, String>();
    } else {
        if (cache.containsKey(o)) {
            return (String) cache.get(o);
        }
    }

    if (o instanceof Collection) {
        int count = 0;
        StringBuilder sb = new StringBuilder(128);
        sb.append("(");
        Collection c = (Collection) o;
        for (Object obj : (c)) {
            if (count > 0) {
                sb.append(", ");
            }
            if (count > 2) {
                sb.append("... ");
                sb.append(c.size() - 3);
                sb.append(" more");
                break;
            }
            sb.append(obj);
            count++;
        }
        sb.append(")");
        return sb.toString();
    } else if (o instanceof Map) {
        Map map = (Map) o;
        int count = 0;
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (Object k : map.keySet()) {
            if (count > 0) {
                sb.append(", ");
            }
            if (count > 2) {
                sb.append("... ");
                sb.append(map.size() - 3);
                sb.append(" more");
                break;
            }
            sb.append(k);
            sb.append("=");
            cache.put(o, o.getClass().getName() + ":" + System.identityHashCode(o));
            sb.append(getResultsString(map.get(k), cache));
            count++;
        }
        sb.append("}");
        return sb.toString();
    } else if (o.getClass().isArray()) {
        int length = Array.getLength(o);
        if (length == 0) {
            return "[]";
        }
        StringBuilder sb = new StringBuilder(128);
        sb.append("[");
        for (int i = 0; i < length; i++) {

            if (i != 0) {
                sb.append(", ");
            }

            if (i > 2) {
                sb.append("... ");
                sb.append(i - 2);
                sb.append(" more");
                break;
            }
            sb.append(Array.get(o, i));
        }
        sb.append("]");
        return sb.toString();
    } else {
        return o.toString();
    }
}