Example usage for java.lang Class getComponentType

List of usage examples for java.lang Class getComponentType

Introduction

In this page you can find the example usage for java.lang Class getComponentType.

Prototype

public Class<?> getComponentType() 

Source Link

Document

Returns the Class representing the component type of an array.

Usage

From source file:jef.database.DefaultSqlProcessor.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public Object collectValueToContainer(List<? extends IQueryableEntity> records, Class<?> containerType,
        String targetField) {/*w  ww .j  a va 2s. c o m*/
    Collection c = null;
    if (containerType == Set.class) {
        c = new HashSet();
    } else if (containerType == List.class || containerType.isArray()) {
        c = new ArrayList();
    } else {
        if (!records.isEmpty()) {
            BeanWrapper bean = BeanWrapper.wrap(records.get(0));
            return bean.getPropertyValue(targetField);
        }
        return null;
        // throw new IllegalArgumentException(containerType +
        // " is not a known collection type.");
    }
    for (IQueryableEntity d : records) {
        BeanWrapper bean = BeanWrapper.wrap(d);
        c.add(bean.getPropertyValue(targetField));
    }
    if (containerType.isArray()) {
        return c.toArray((Object[]) Array.newInstance(containerType.getComponentType(), c.size()));
    } else {
        return c;
    }
}

From source file:javadz.beanutils.LazyDynaBean.java

/**
 * Create a new Instance of an 'Indexed' Property
 * @param name The name of the property/*  w ww .j  ava2s  . co m*/
 * @param type The class of the property
 * @return The new value
 */
protected Object createIndexedProperty(String name, Class type) {

    // Create the indexed object
    Object indexedProperty = null;

    if (type == null) {

        indexedProperty = defaultIndexedProperty(name);

    } else if (type.isArray()) {

        indexedProperty = Array.newInstance(type.getComponentType(), 0);

    } else if (List.class.isAssignableFrom(type)) {
        if (type.isInterface()) {
            indexedProperty = defaultIndexedProperty(name);
        } else {
            try {
                indexedProperty = type.newInstance();
            } catch (Exception ex) {
                throw new IllegalArgumentException("Error instantiating indexed property of type '"
                        + type.getName() + "' for '" + name + "' " + ex);
            }
        }
    } else {

        throw new IllegalArgumentException(
                "Non-indexed property of type '" + type.getName() + "' for '" + name + "'");
    }

    return indexedProperty;

}

From source file:adalid.core.programmers.AbstractJavaProgrammer.java

protected String javaLangLess(Class<?> type) {
    return type == null ? "Object"
            : type.isArray() ? javaLangLess(type.getComponentType()) + "[]"
                    : StringUtils.removeStart(type.getName(), "java.lang.");
}

From source file:com.link_intersystems.lang.reflect.Class2.java

/**
 * The string representation of a {@link Class2}.
 *
 * <ul>//from  w  w  w.  j  a  va  2 s. com
 * <li>
 * Types are represented by their canonical name. If a type is a
 * &quot;well-known&quot; type (all types in java.lang) the type's simple
 * name is used. E.g. String - java.util.List.</li>
 * <ul>
 * <li>
 * Arrays are represented by their type and appended by []. E.g. int[]
 * String[] java.beans.PropertyDescriptor[].</li>
 *
 * @param wellKnownPackages
 *            packages that are &quot;well known&quot; will not be printed
 *            in the string representation. E.g. if java.lang is defined as
 *            well known the Class2 that represents a String class will be
 *            printed just as &quot;String&quot; and not java.lang.String.
 *
 * @return a string representation of this {@link Class2};
 * @since 1.0.0.0
 */
public String toString(String... wellKnownPackages) {
    Assert.notNull("wellKnownPackages", wellKnownPackages);
    StringBuilder toStringBuilder = new StringBuilder();
    Class<?> clazz = getType();
    boolean isArray = clazz.isArray();
    if (isArray) {
        clazz = clazz.getComponentType();
    }
    Package clazzPackage = clazz.getPackage();
    String packageName = StringUtils.EMPTY;
    if (clazzPackage != null) {
        packageName = clazzPackage.getName();
    }

    boolean isWellKnownPackage = Arrays.binarySearch(wellKnownPackages, packageName) > -1;

    if (isWellKnownPackage) {
        toStringBuilder.append(clazz.getSimpleName());
    } else {
        toStringBuilder.append(clazz.getCanonicalName());
    }

    TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
    String typeParametersToString = typeParametersToString(typeParameters);
    toStringBuilder.append(typeParametersToString);

    if (isArray) {
        toStringBuilder.append("[]");
    }
    return toStringBuilder.toString();
}

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

/**
 * Serialize an element that is an array.
 * @param name is the element name/*from w ww .  j  ava 2s  .com*/
 * @param attributes are the attributes...serialize is free to add more.
 * @param value is the value
 * @param context is the SerializationContext
 */
public void serialize(QName name, Attributes attributes, Object value, SerializationContext context)
        throws IOException {
    if (value == null)
        throw new IOException(Messages.getMessage("cantDoNullArray00"));

    MessageContext msgContext = context.getMessageContext();
    SchemaVersion schema = SchemaVersion.SCHEMA_2001;
    SOAPConstants soap = SOAPConstants.SOAP11_CONSTANTS;
    boolean encoded = context.isEncoded();

    if (msgContext != null) {
        schema = msgContext.getSchemaVersion();
        soap = msgContext.getSOAPConstants();
    }

    Class cls = value.getClass();
    Collection list = null;

    if (!cls.isArray()) {
        if (!(value instanceof Collection)) {
            throw new IOException(Messages.getMessage("cantSerialize00", cls.getName()));
        }
        list = (Collection) value;
    }

    // Get the componentType of the array/list
    Class componentClass;
    if (list == null) {
        componentClass = cls.getComponentType();
    } else {
        componentClass = Object.class;
    }

    // Get the QName of the componentType
    // if it wasn't passed in from the constructor
    QName componentTypeQName = this.componentType;

    // Check to see if componentType is also an array.
    // If so, set the componentType to the most nested non-array
    // componentType.  Increase the dims string by "[]"
    // each time through the loop.
    // Note from Rich Scheuerle:
    //    This won't handle Lists of Lists or
    //    arrays of Lists....only arrays of arrays.
    String dims = "";

    if (componentTypeQName != null) {
        // if we have a Type QName at this point,
        // this is because ArraySerializer has been instanciated with it
        TypeMapping tm = context.getTypeMapping();
        SerializerFactory factory = (SerializerFactory) tm.getSerializer(componentClass, componentTypeQName);
        while (componentClass.isArray() && factory instanceof ArraySerializerFactory) {
            ArraySerializerFactory asf = (ArraySerializerFactory) factory;
            componentClass = componentClass.getComponentType();
            QName componentType = null;
            if (asf.getComponentType() != null) {
                componentType = asf.getComponentType();
                if (encoded) {
                    componentTypeQName = componentType;
                }
            }
            // update factory with the new values
            factory = (SerializerFactory) tm.getSerializer(componentClass, componentType);
            if (soap == SOAPConstants.SOAP12_CONSTANTS)
                dims += "* ";
            else
                dims += "[]";
        }
    } else {
        // compatibility mode
        while (componentClass.isArray()) {
            componentClass = componentClass.getComponentType();
            if (soap == SOAPConstants.SOAP12_CONSTANTS)
                dims += "* ";
            else
                dims += "[]";
        }
    }

    // Try the current XML type from the context
    if (componentTypeQName == null) {
        componentTypeQName = context.getCurrentXMLType();
        if (componentTypeQName != null) {
            if ((componentTypeQName.equals(xmlType) || componentTypeQName.equals(Constants.XSD_ANYTYPE)
                    || componentTypeQName.equals(soap.getArrayType()))) {
                componentTypeQName = null;
            }
        }
    }

    if (componentTypeQName == null) {
        componentTypeQName = context.getItemType();
    }

    // Then check the type mapping for the class
    if (componentTypeQName == null) {
        componentTypeQName = context.getQNameForClass(componentClass);
    }

    // If still not found, look at the super classes
    if (componentTypeQName == null) {
        Class searchCls = componentClass;
        while (searchCls != null && componentTypeQName == null) {
            searchCls = searchCls.getSuperclass();
            componentTypeQName = context.getQNameForClass(searchCls);
        }
        if (componentTypeQName != null) {
            componentClass = searchCls;
        }
    }

    // Still can't find it?  Throw an error.
    if (componentTypeQName == null) {
        throw new IOException(Messages.getMessage("noType00", componentClass.getName()));
    }

    int len = (list == null) ? Array.getLength(value) : list.size();
    String arrayType = "";
    int dim2Len = -1;
    if (encoded) {
        if (soap == SOAPConstants.SOAP12_CONSTANTS) {
            arrayType = dims + len;
        } else {
            arrayType = dims + "[" + len + "]";
        }

        // Discover whether array can be serialized directly as a two-dimensional
        // array (i.e. arrayType=int[2,3]) versus an array of arrays.
        // Benefits:
        //   - Less text passed on the wire.
        //   - Easier to read wire format
        //   - Tests the deserialization of multi-dimensional arrays.
        // Drawbacks:
        //   - Is not safe!  It is possible that the arrays are multiply
        //     referenced.  Transforming into a 2-dim array will cause the
        //     multi-referenced information to be lost.  Plus there is no
        //     way to determine whether the arrays are multi-referenced.
        //   - .NET currently (Dec 2002) does not support 2D SOAP-encoded arrays
        //
        // OLD Comment as to why this was ENABLED:
        // It is necessary for
        // interoperability (echo2DStringArray).  It is 'safe' for now
        // because Axis treats arrays as non multi-ref (see the note
        // in SerializationContext.isPrimitive(...) )
        // More complicated processing is necessary for 3-dim arrays, etc.
        //
        // Axis 1.1 - December 2002
        // Turned this OFF because Microsoft .NET can not deserialize
        // multi-dimensional SOAP-encoded arrays, and this interopability
        // is pretty high visibility. Make it a global configuration parameter:
        //  <parameter name="enable2DArrayEncoding" value="true"/>    (tomj)
        //

        // Check the message context to see if we should turn 2D processing ON
        // Default is OFF
        boolean enable2Dim = false;

        // Vidyanand : added this check
        if (msgContext != null) {
            enable2Dim = JavaUtils
                    .isTrueExplicitly(msgContext.getProperty(AxisEngine.PROP_TWOD_ARRAY_ENCODING));
        }

        if (enable2Dim && !dims.equals("")) {
            if (cls.isArray() && len > 0) {
                boolean okay = true;
                // Make sure all of the component arrays are the same size
                for (int i = 0; i < len && okay; i++) {

                    Object elementValue = Array.get(value, i);
                    if (elementValue == null)
                        okay = false;
                    else if (dim2Len < 0) {
                        dim2Len = Array.getLength(elementValue);
                        if (dim2Len <= 0) {
                            okay = false;
                        }
                    } else if (dim2Len != Array.getLength(elementValue)) {
                        okay = false;
                    }
                }
                // Update the arrayType to use mult-dim array encoding
                if (okay) {
                    dims = dims.substring(0, dims.length() - 2);
                    if (soap == SOAPConstants.SOAP12_CONSTANTS)
                        arrayType = dims + len + " " + dim2Len;
                    else
                        arrayType = dims + "[" + len + "," + dim2Len + "]";
                } else {
                    dim2Len = -1;
                }
            }
        }
    }

    // Need to distinguish if this is array processing for an
    // actual schema array or for a maxOccurs usage.
    // For the maxOccurs case, the currentXMLType of the context is
    // the same as the componentTypeQName.
    QName itemQName = context.getItemQName();
    boolean maxOccursUsage = !encoded && itemQName == null
            && componentTypeQName.equals(context.getCurrentXMLType());

    if (encoded) {
        AttributesImpl attrs;
        if (attributes == null) {
            attrs = new AttributesImpl();
        } else if (attributes instanceof AttributesImpl) {
            attrs = (AttributesImpl) attributes;
        } else {
            attrs = new AttributesImpl(attributes);
        }

        String compType = context.attributeQName2String(componentTypeQName);

        if (attrs.getIndex(soap.getEncodingURI(), soap.getAttrItemType()) == -1) {
            String encprefix = context.getPrefixForURI(soap.getEncodingURI());

            if (soap != SOAPConstants.SOAP12_CONSTANTS) {
                compType = compType + arrayType;

                attrs.addAttribute(soap.getEncodingURI(), soap.getAttrItemType(), encprefix + ":arrayType",
                        "CDATA", compType);

            } else {
                attrs.addAttribute(soap.getEncodingURI(), soap.getAttrItemType(), encprefix + ":itemType",
                        "CDATA", compType);

                attrs.addAttribute(soap.getEncodingURI(), "arraySize", encprefix + ":arraySize", "CDATA",
                        arrayType);
            }
        }

        // Force type to be SOAP_ARRAY for all array serialization.
        //
        // There are two choices here:
        // Force the type to type=SOAP_ARRAY
        //   Pros:  More interop test successes.
        //   Cons:  Since we have specific type information it
        //          is more correct to use it.  Plus the specific
        //          type information may be important on the
        //          server side to disambiguate overloaded operations.
        // Use the specific type information:
        //   Pros:  The specific type information is more correct
        //          and may be useful for operation overloading.
        //   Cons:  More interop test failures (as of 2/6/2002).
        //
        String qname = context.getPrefixForURI(schema.getXsiURI(), "xsi") + ":type";
        QName soapArray;
        if (soap == SOAPConstants.SOAP12_CONSTANTS) {
            soapArray = Constants.SOAP_ARRAY12;
        } else {
            soapArray = Constants.SOAP_ARRAY;
        }

        int typeI = attrs.getIndex(schema.getXsiURI(), "type");
        if (typeI != -1) {
            attrs.setAttribute(typeI, schema.getXsiURI(), "type", qname, "CDATA",
                    context.qName2String(soapArray));
        } else {
            attrs.addAttribute(schema.getXsiURI(), "type", qname, "CDATA", context.qName2String(soapArray));
        }

        attributes = attrs;
    }

    // For the maxOccurs case, each item is named with the QName
    // we got in the arguments.  For normal array case, we write an element with
    // that QName, and then serialize each item as <item>
    QName elementName = name;
    Attributes serializeAttr = attributes;
    if (!maxOccursUsage) {
        serializeAttr = null; // since we are putting them here
        context.startElement(name, attributes);
        if (itemQName != null)
            elementName = itemQName;
        else if (componentQName != null)
            elementName = componentQName;
    }

    if (dim2Len < 0) {
        // Normal case, serialize each array element
        if (list == null) {
            for (int index = 0; index < len; index++) {
                Object aValue = Array.get(value, index);

                // Serialize the element.
                context.serialize(elementName,
                        (serializeAttr == null ? serializeAttr : new AttributesImpl(serializeAttr)), aValue,
                        componentTypeQName, componentClass); // prefered type QName
            }
        } else {
            for (Iterator iterator = list.iterator(); iterator.hasNext();) {
                Object aValue = iterator.next();

                // Serialize the element.
                context.serialize(elementName,
                        (serializeAttr == null ? serializeAttr : new AttributesImpl(serializeAttr)), aValue,
                        componentTypeQName, componentClass); // prefered type QName
            }
        }
    } else {
        // Serialize as a 2 dimensional array
        for (int index = 0; index < len; index++) {
            for (int index2 = 0; index2 < dim2Len; index2++) {
                Object aValue = Array.get(Array.get(value, index), index2);
                context.serialize(elementName, null, aValue, componentTypeQName, componentClass);
            }
        }
    }

    if (!maxOccursUsage)
        context.endElement();
}

From source file:net.sf.qooxdoo.rpc.RemoteCallUtils.java

/**
 * Converts JSON types to "normal" java types.
 *
 * @param       obj                 the object to convert (must not be
 *                                  <code>null</code>, but can be
 *                                  <code>JSONObject.NULL</code>).
 * @param       targetType          the desired target type (must not be
 *                                  <code>null</code>).
 *
 * @return      the converted object.//w ww  . j a  v  a2 s.  c o  m
 *
 * @exception   IllegalArgumentException    thrown if the desired
 *                                          conversion is not possible.
 */

public Object toJava(Object obj, Class targetType) {
    try {
        if (obj == JSONObject.NULL) {
            if (targetType == Integer.TYPE || targetType == Double.TYPE || targetType == Boolean.TYPE
                    || targetType == Long.TYPE || targetType == Float.TYPE) {
                // null does not work for primitive types
                throw new Exception();
            }
            return null;
        }
        if (obj instanceof JSONArray) {
            Class componentType;
            if (targetType == null || targetType == Object.class) {
                componentType = null;
            } else {
                componentType = targetType.getComponentType();
            }
            JSONArray jsonArray = (JSONArray) obj;
            int length = jsonArray.length();
            Object retVal = Array.newInstance((componentType == null ? Object.class : componentType), length);
            for (int i = 0; i < length; ++i) {
                Array.set(retVal, i, toJava(jsonArray.get(i), componentType));
            }
            return retVal;
        }
        if (obj instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) obj;
            JSONArray names = jsonObject.names();
            if (targetType == Map.class || targetType == HashMap.class || targetType == null
                    || targetType == Object.class) {
                HashMap retVal = new HashMap();
                if (names != null) {
                    int length = names.length();
                    String name;
                    for (int i = 0; i < length; ++i) {
                        name = names.getString(i);
                        retVal.put(name, toJava(jsonObject.get(name), null));
                    }
                }
                return retVal;
            }
            Object bean;
            String requestedTypeName = jsonObject.optString("class", null);
            if (requestedTypeName != null) {
                Class clazz = resolveClassHint(requestedTypeName, targetType);
                if (clazz == null || !targetType.isAssignableFrom(clazz)) {
                    throw new Exception();
                }
                bean = clazz.newInstance();
                // TODO: support constructor parameters
            } else {
                bean = targetType.newInstance();
            }
            if (names != null) {
                int length = names.length();
                String name;
                PropertyDescriptor desc;
                for (int i = 0; i < length; ++i) {
                    name = names.getString(i);
                    if (!"class".equals(name)) {
                        desc = PropertyUtils.getPropertyDescriptor(bean, name);
                        if (desc != null && desc.getWriteMethod() != null) {
                            PropertyUtils.setSimpleProperty(bean, name,
                                    toJava(jsonObject.get(name), desc.getPropertyType()));
                        }
                    }
                }
            }
            return bean;
        }
        if (targetType == null || targetType == Object.class) {
            return obj;
        }
        Class actualTargetType;
        Class sourceType = obj.getClass();
        if (targetType == Integer.TYPE) {
            actualTargetType = Integer.class;
        } else if (targetType == Boolean.TYPE) {
            actualTargetType = Boolean.class;
        } else if ((targetType == Double.TYPE || targetType == Double.class)
                && Number.class.isAssignableFrom(sourceType)) {
            return new Double(((Number) obj).doubleValue());
            // TODO: maybe return obj directly if it's a Double 
        } else if ((targetType == Float.TYPE || targetType == Float.class)
                && Number.class.isAssignableFrom(sourceType)) {
            return new Float(((Number) obj).floatValue());
        } else if ((targetType == Long.TYPE || targetType == Long.class)
                && Number.class.isAssignableFrom(sourceType)) {
            return new Long(((Number) obj).longValue());
        } else {
            actualTargetType = targetType;
        }
        if (!actualTargetType.isAssignableFrom(sourceType)) {
            throw new Exception();
        }
        return obj;
    } catch (IllegalArgumentException e) {
        throw e;
    } catch (Exception e) {
        throw new IllegalArgumentException("Cannot convert " + (obj == null ? null : obj.getClass().getName())
                + " to " + (targetType == null ? null : targetType.getName()));
    }
}

From source file:net.sourceforge.vulcan.web.struts.forms.PluginConfigForm.java

public void introspect(HttpServletRequest request) throws IntrospectionException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, InstantiationException {
    Class<?> cls = null;

    if ("pluginConfig".equals(focus)) {
        cls = pluginConfig.getClass();//from w ww  . j  a v a  2 s. co  m
        this.breadCrumbs.clear();
        this.breadCrumbs.add("Setup");

        if (isProjectPlugin()) {
            this.breadCrumbs.add("Projects");
            this.breadCrumbs.add(projectName);
            this.breadCrumbs.add(this.pluginConfig.getPluginName());
        } else {
            this.breadCrumbs.add("Plugins");
            this.breadCrumbs.add(this.pluginConfig.getPluginName());
        }
    } else {
        cls = PropertyUtils.getPropertyType(this, focus);
        if (cls.isArray()) {
            cls = cls.getComponentType();
        }
    }

    final String prefix = focus + ".";
    final PropertyDescriptor[] pds;

    if (PluginConfigDto.class.isAssignableFrom(cls)) {
        final PluginConfigDto pluginConfig = (PluginConfigDto) getFocusObject();
        final List<PropertyDescriptor> tmp = pluginConfig.getPropertyDescriptors(request.getLocale());
        pds = tmp.toArray(new PropertyDescriptor[tmp.size()]);

        if (pluginConfig instanceof PluginProfileDto) {
            ((PluginProfileDto) pluginConfig).checkPoint();
        }
    } else {
        final BeanInfo beanInfo = Introspector.getBeanInfo(cls);
        Introspector.flushFromCaches(cls);
        pds = beanInfo.getPropertyDescriptors();
    }

    if (isNested()) {
        for (PropertyDescriptor pd : propertyDescriptors) {
            if (focus.startsWith(pd.getName())) {
                breadCrumbs.add(pd.getDisplayName());
            }
        }
    }

    types.clear();
    choices.clear();
    propertyDescriptors.clear();
    hiddenPasswords.clear();

    for (PropertyDescriptor pd : pds) {
        final String name = prefix + pd.getName();
        final PropertyDescriptor cp = new PropertyDescriptor(pd.getName(), pd.getReadMethod(),
                pd.getWriteMethod());
        cp.setShortDescription(pd.getShortDescription());
        cp.setDisplayName(pd.getDisplayName());
        cp.setName(name);
        propertyDescriptors.add(cp);
        types.put(name, getTypeAndPrepare(name, pd));
    }

    putBreadCrumbsInRequest(request);
}

From source file:ch.systemsx.cisd.openbis.generic.server.authorization.DefaultReturnValueFilter.java

@Private
final <T> Object proceed(final PersonPE person, final Method method, final Object returnValue,
        final IValidator<T> validator) {
    final String validatorClassName = validator.getClass().getName();
    final Class<?> returnValueClass = returnValue.getClass();
    if (returnValue instanceof List<?>) {
        final List<T> list = castToList(returnValue);
        try {/*w ww  .  ja v  a2 s . co m*/
            return proceedList(person, method, list, validator);
        } catch (final ClassCastException ex) {
            throw new IllegalArgumentException(
                    String.format("Given validator class '%s' " + "and list type '%s' are not compatible.",
                            validatorClassName, list.get(0).getClass().getName()));
        }
    } else if (returnValueClass.isArray()) {
        final T[] array = castToArray(returnValue);
        try {
            return proceedArray(person, method, validator, array);
        } catch (final ClassCastException e) {
            throw new IllegalArgumentException(
                    String.format("Given validator class '%s' " + "and array type '%s' are not compatible.",
                            validatorClassName, returnValueClass.getComponentType().getName()));
        }
    } else {
        final T value = cast(returnValue);
        try {
            return proceedValue(person, method, returnValue, validator, value);
        } catch (final ClassCastException ex) {
            throw new IllegalArgumentException(String.format(
                    "Given validator class '%s' " + "and return value type '%s' are not compatible.",
                    validatorClassName, returnValueClass.getName()));
        }
    }
}

From source file:com.glaf.core.util.ReflectUtils.java

private static Object getEmptyObject(Class<?> returnType, Map<Class<?>, Object> emptyInstances, int level) {
    if (level > 2)
        return null;
    if (returnType == null) {
        return null;
    } else if (returnType == boolean.class || returnType == Boolean.class) {
        return false;
    } else if (returnType == char.class || returnType == Character.class) {
        return '\0';
    } else if (returnType == byte.class || returnType == Byte.class) {
        return (byte) 0;
    } else if (returnType == short.class || returnType == Short.class) {
        return (short) 0;
    } else if (returnType == int.class || returnType == Integer.class) {
        return 0;
    } else if (returnType == long.class || returnType == Long.class) {
        return 0L;
    } else if (returnType == float.class || returnType == Float.class) {
        return 0F;
    } else if (returnType == double.class || returnType == Double.class) {
        return 0D;
    } else if (returnType.isArray()) {
        return Array.newInstance(returnType.getComponentType(), 0);
    } else if (returnType.isAssignableFrom(ArrayList.class)) {
        return new java.util.ArrayList<Object>(0);
    } else if (returnType.isAssignableFrom(HashSet.class)) {
        return new HashSet<Object>(0);
    } else if (returnType.isAssignableFrom(HashMap.class)) {
        return new java.util.concurrent.ConcurrentHashMap<Object, Object>(0);
    } else if (String.class.equals(returnType)) {
        return "";
    } else if (!returnType.isInterface()) {
        try {//from ww w.  j a  va  2s. c  o m
            Object value = emptyInstances.get(returnType);
            if (value == null) {
                value = returnType.newInstance();
                emptyInstances.put(returnType, value);
            }
            Class<?> cls = value.getClass();
            while (cls != null && cls != Object.class) {
                Field[] fields = cls.getDeclaredFields();
                for (Field field : fields) {
                    Object property = getEmptyObject(field.getType(), emptyInstances, level + 1);
                    if (property != null) {
                        try {
                            if (!field.isAccessible()) {
                                field.setAccessible(true);
                            }
                            field.set(value, property);
                        } catch (Throwable e) {
                        }
                    }
                }
                cls = cls.getSuperclass();
            }
            return value;
        } catch (Throwable e) {
            return null;
        }
    } else {
        return null;
    }
}

From source file:org.kohsuke.github.Requester.java

private <T> T parse(Class<T> type, T instance) throws IOException {
    InputStreamReader r = null;//from  w  w w . j av  a 2 s  .  c o  m
    int responseCode = -1;
    String responseMessage = null;
    try {
        responseCode = uc.getResponseCode();
        responseMessage = uc.getResponseMessage();
        if (responseCode == 304) {
            return null; // special case handling for 304 unmodified, as the content will be ""
        }
        if (responseCode == 204 && type != null && type.isArray()) {
            // no content
            return type.cast(Array.newInstance(type.getComponentType(), 0));
        }

        r = new InputStreamReader(wrapStream(uc.getInputStream()), "UTF-8");
        String data = IOUtils.toString(r);
        if (type != null)
            try {
                return MAPPER.readValue(data, type);
            } catch (JsonMappingException e) {
                throw (IOException) new IOException("Failed to deserialize " + data).initCause(e);
            }
        if (instance != null)
            return MAPPER.readerForUpdating(instance).<T>readValue(data);
        return null;
    } catch (FileNotFoundException e) {
        // java.net.URLConnection handles 404 exception has FileNotFoundException, don't wrap exception in HttpException
        // to preserve backward compatibility
        throw e;
    } catch (IOException e) {
        throw new HttpException(responseCode, responseMessage, uc.getURL(), e);
    } finally {
        IOUtils.closeQuietly(r);
    }
}