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:com.seleniumtests.reporter.SeleniumTestsReporter.java

protected int getDim(Class<?> cls) {
    int dim = 0;/* w w w . ja va 2s  .  c  om*/

    while (cls.isArray()) {
        dim++;
        cls = cls.getComponentType();
    }

    return dim;
}

From source file:com.gdevelop.gwt.syncrpc.SyncClientSerializationStreamReader.java

private Object instantiate(Class<?> customSerializer, Class<?> instanceClass)
        throws InstantiationException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, NoSuchMethodException, SerializationException {
    if (customSerializer != null) {
        for (Method method : customSerializer.getMethods()) {
            if ("instantiate".equals(method.getName())) {
                return method.invoke(null, this);
            }/*  w  w w  .j a  va2  s .co m*/
        }
        // Ok to not have one.
    }

    if (instanceClass.isArray()) {
        int length = readInt();
        // We don't pre-allocate the array; this prevents an allocation attack
        return new BoundedList<Object>(instanceClass.getComponentType(), length);
    } else if (instanceClass.isEnum()) {
        Enum<?>[] enumConstants = (Enum[]) instanceClass.getEnumConstants();
        int ordinal = readInt();
        assert (ordinal >= 0 && ordinal < enumConstants.length);
        return enumConstants[ordinal];
    } else {
        Constructor<?> constructor = instanceClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        return constructor.newInstance();
    }
}

From source file:com.amalto.core.metadata.ClassRepository.java

private TypeMetadata loadClass(Class clazz) {
    String typeName = getTypeName(clazz);
    if (getType(typeName) != null) { // If already defined return it.
        return getType(typeName);
    } else if (getNonInstantiableType(StringUtils.EMPTY, typeName) != null) {
        return getNonInstantiableType(StringUtils.EMPTY, typeName);
    }//  w  ww.j  a v a  2s. c om
    entityToJavaClass.put(typeName, clazz);
    if (Map.class.isAssignableFrom(clazz)) {
        return MAP_TYPE;
    }
    if (ArrayListHolder.class.equals(clazz)) {
        typeName = typeName + listCounter++;
    }
    boolean isEntity = typeStack.isEmpty();
    ComplexTypeMetadata classType = new ComplexTypeMetadataImpl(StringUtils.EMPTY, typeName, isEntity);
    addTypeMetadata(classType);
    typeStack.push(classType);
    String keyFieldName = ""; //$NON-NLS-1$
    if (isEntity && ObjectPOJO.class.isAssignableFrom(clazz)) {
        SimpleTypeFieldMetadata keyField = new SimpleTypeFieldMetadata(typeStack.peek(), true, false, true,
                "unique-id", //$NON-NLS-1$
                STRING, Collections.<String>emptyList(), Collections.<String>emptyList(),
                Collections.<String>emptyList(), StringUtils.EMPTY);
        keyField.setData(LINK, "PK/unique-id"); //$NON-NLS-1$
        classType.addField(keyField);
    } else if (isEntity) {
        keyFieldName = "unique-id"; //$NON-NLS-1$
    }
    // Class is abstract / interface: load sub classes
    if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
        Iterable<Class> subClasses = getSubclasses(clazz);
        ComplexTypeMetadata superType = typeStack.peek();
        if (superType.isInstantiable()) {
            typeStack.clear();
        }
        for (Class subClass : subClasses) {
            TypeMetadata typeMetadata = loadClass(subClass);
            typeMetadata.setInstantiable(superType.isInstantiable());
            typeMetadata.addSuperType(superType);
        }
        if (superType.isInstantiable()) {
            typeStack.push(superType);
        }
    }
    // Analyze methods
    Method[] classMethods = getMethods(clazz);
    for (Method declaredMethod : classMethods) {
        if (!Modifier.isStatic(declaredMethod.getModifiers())) {
            if (isBeanMethod(declaredMethod) && isClassMethod(clazz, declaredMethod)) {
                String fieldName = getName(declaredMethod);
                if (typeStack.peek().hasField(fieldName)) {
                    continue; // TODO Avoid override of fields (like PK)
                }
                Class<?> returnType = declaredMethod.getReturnType();
                FieldMetadata newField;
                boolean isMany = false;
                boolean isKey = keyFieldName.equals(fieldName);
                if (Iterable.class.isAssignableFrom(returnType)) {
                    returnType = listItemType != null ? listItemType
                            : getListItemClass(declaredMethod, returnType);
                    listItemType = null;
                    isMany = true;
                } else if (ArrayListHolder.class.isAssignableFrom(returnType)) {
                    listItemType = getListItemClass(declaredMethod, returnType);
                    isMany = false;
                } else if (Map.class.isAssignableFrom(returnType)) {
                    isMany = true;
                } else if (returnType.isArray()) {
                    isMany = true;
                    returnType = ((Class) returnType.getComponentType());
                } else if (returnType.getName().startsWith("org.w3c.")) { //$NON-NLS-1$
                    // TODO Serialized XML to string column
                    continue;
                } else if (Class.class.equals(returnType)) {
                    continue;
                } else if (returnType.getPackage() != null
                        && returnType.getPackage().getName().startsWith("java.io")) { //$NON-NLS-1$
                    continue;
                }
                if (returnType.isPrimitive() || returnType.getName().startsWith(JAVA_LANG_PREFIX)) {
                    String fieldTypeName = returnType.getName().toLowerCase();
                    if (fieldTypeName.startsWith(JAVA_LANG_PREFIX)) {
                        fieldTypeName = StringUtils.substringAfter(fieldTypeName, JAVA_LANG_PREFIX);
                    }
                    TypeMetadata fieldType;
                    if (Types.BYTE.equals(fieldTypeName) && isMany) {
                        fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI,
                                Types.BASE64_BINARY);
                    } else {
                        fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, fieldTypeName);
                    }
                    newField = new SimpleTypeFieldMetadata(typeStack.peek(), isKey, isMany, isKey, fieldName,
                            fieldType, Collections.<String>emptyList(), Collections.<String>emptyList(),
                            Collections.<String>emptyList(), StringUtils.EMPTY);
                    LongString annotation = declaredMethod.getAnnotation(LongString.class);
                    if (Types.STRING.equals(fieldTypeName) && annotation != null) {
                        fieldType.setData(MetadataRepository.DATA_MAX_LENGTH,
                                String.valueOf(Integer.MAX_VALUE));
                        if (annotation.preferLongVarchar()) {
                            fieldType.setData(LongString.PREFER_LONGVARCHAR, Boolean.TRUE);
                        }
                    }
                } else {
                    ComplexTypeMetadata fieldType;
                    if (Map.class.isAssignableFrom(returnType)) {
                        fieldType = MAP_TYPE;
                    } else {
                        fieldType = (ComplexTypeMetadata) loadClass(returnType);
                    }
                    if (!isEntity || !fieldType.isInstantiable()) {
                        newField = new ContainedTypeFieldMetadata(typeStack.peek(), isMany, false, fieldName,
                                new SoftTypeRef(this, StringUtils.EMPTY, fieldType.getName(), false),
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                Collections.<String>emptyList(), StringUtils.EMPTY);
                    } else {
                        newField = new ReferenceFieldMetadata(typeStack.peek(), false, isMany, false, fieldName,
                                fieldType, fieldType.getField("unique-id"), //$NON-NLS-1$
                                Collections.<FieldMetadata>emptyList(), StringUtils.EMPTY, true, false, STRING,
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                Collections.<String>emptyList(), StringUtils.EMPTY, StringUtils.EMPTY);
                    }
                }
                typeStack.peek().addField(newField);
            }
        }
    }

    typeStack.peek().addField(new SimpleTypeFieldMetadata(typeStack.peek(), false, false, false, "digest", //$NON-NLS-1$
            new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, Types.STRING),
            Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(),
            StringUtils.EMPTY));

    return typeStack.pop();
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMinimalMethodMarshaller.java

public Object demarshalResponse(Message message, Object[] signatureArgs, OperationDescription operationDesc)
        throws WebServiceException {

    if (log.isDebugEnabled()) {
        log.debug("enter demarshalResponse operationDesc = " + operationDesc.getName());
    }/*from  ww w. j a  v a2s.  co m*/
    EndpointInterfaceDescription ed = operationDesc.getEndpointInterfaceDescription();
    EndpointDescription endpointDesc = ed.getEndpointDescription();

    // Note all exceptions are caught and rethrown with a WebServiceException
    try {
        // Sample Document message
        // ..
        // <soapenv:body>
        //    <m:operationResponse ... >
        //       <param>hello</param>
        //    </m:operationResponse>
        // </soapenv:body>
        //
        // Important points.
        //   1) There is no operation element in the message
        //   2) The data blocks are located underneath the body element. 
        //   3) The name of the data block (m:operationResponse) is defined by the schema.
        //      It matches the operation name + "Response", and it has a corresponding JAXB element.
        //      This element is called the wrapper element
        //   4) The parameters are (param) are child elements of the wrapper element.
        //   5) For "minimal" the pojo bean representing the OperationResponse is missing

        ParameterDescription[] pds = operationDesc.getParameterDescriptions();
        MarshalServiceRuntimeDescription marshalDesc = MethodMarshallerUtils.getMarshalDesc(endpointDesc);
        TreeSet<String> packages = marshalDesc.getPackages();

        // Indicate that the style is Document. 
        message.setStyle(Style.DOCUMENT);
        message.setIndirection(1);

        // Create an array of indices indicating where each parameter is located in the body
        // A -1 indicates that the parameter is not in the body
        int[] firstIndex = new int[pds.length];
        int[] lastIndex = new int[pds.length];
        for (int i = 0; i < firstIndex.length; i++) {
            firstIndex[i] = -1;
            lastIndex[i] = -1;
        }
        calculateBodyIndex(firstIndex, lastIndex, pds, message.getBodyBlockQNames());

        int firstBodyParamIndex = -1;

        for (int i = 0; i < pds.length; i++) {
            if (pds[i].getMode() == Mode.OUT || pds[i].getMode() == Mode.INOUT) {
                if (firstIndex[i] >= 0 && firstBodyParamIndex == -1) {
                    firstBodyParamIndex = firstIndex[i];
                }
            }
        }

        // Get the return value.
        Class returnType = operationDesc.getResultActualType();
        Class returnComponentType = null;
        if (returnType.isArray()) {
            returnComponentType = returnType.getComponentType();
        } else if (returnType.isAssignableFrom(List.class)) {
            returnComponentType = getComponentType(null, operationDesc, marshalDesc);
        } else {
            returnComponentType = null;
        }
        Object returnValue = null;
        boolean hasReturnInBody = false;
        if (returnType != void.class) {
            // If the webresult is in the header, we need the name of the header so that we can find it.
            Element returnElement = null;
            if (operationDesc.isResultHeader()) {
                returnElement = getReturnElementForDocLitWrappedMinimal(packages, message, returnType,
                        returnComponentType, operationDesc.isListType(), true, // is a header
                        operationDesc.getResultTargetNamespace(),
                        // header ns
                        operationDesc.getResultPartName(), // header local part
                        MethodMarshallerUtils.numOutputBodyParams(pds) > 0, firstBodyParamIndex);

            } else {
                returnElement = getReturnElementForDocLitWrappedMinimal(packages, message, returnType,
                        returnComponentType, operationDesc.isListType(), false, null, null,
                        MethodMarshallerUtils.numOutputBodyParams(pds) > 0, firstBodyParamIndex);
                hasReturnInBody = true;

            }
            returnValue = returnElement.getTypeValue();
        }

        // We want to use "by Java Type" unmarshalling for 
        // all objects
        Class[] javaTypes = new Class[pds.length];
        Class[] componentJavaTypes = new Class[pds.length];
        for (int i = 0; i < pds.length; i++) {
            ParameterDescription pd = pds[i];
            Class type = pd.getParameterActualType();

            if (type.isArray()) {
                componentJavaTypes[i] = type.getComponentType();
            } else if (type.isAssignableFrom(List.class)) {
                componentJavaTypes[i] = getComponentType(pd, operationDesc, marshalDesc);
            } else {
                componentJavaTypes[i] = null;
            }
            javaTypes[i] = type;
        }

        // Unmarshall the ParamValues from the Message
        List<PDElement> pvList = getPDElementsForDocLitWrappedMinimal(pds, message, packages, false, // output
                hasReturnInBody, javaTypes, componentJavaTypes, firstIndex, lastIndex);

        // Populate the response Holders
        MethodMarshallerUtils.updateResponseSignatureArgs(pds, pvList, signatureArgs);

        if (log.isDebugEnabled()) {
            log.debug("exit demarshalResponse");
        }
        return returnValue;
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("fail demarshalResponse e=" + e);
            log.debug(" " + JavaUtils.stackToString(e));
        }
        throw ExceptionFactory.makeWebServiceException(e);
    }
}

From source file:org.evosuite.junit.TestSuiteWriter.java

/**
 * Determine packages that need to be imported in the JUnit file
 * /*  ww  w.  j  ava  2 s .  c  o  m*/
 * @param results
 *            a {@link java.util.List} object.
 * @return a {@link java.lang.String} object.
 */
protected String getImports(List<ExecutionResult> results) {
    StringBuilder builder = new StringBuilder();
    Set<Class<?>> imports = new HashSet<Class<?>>();
    boolean wasSecurityException = hasAnySecurityException(results);

    for (ExecutionResult result : results) {
        result.test.accept(visitor);

        // TODO: This should be unnecessary 
        // Iterate over declared exceptions to make sure they are known to the visitor
        /*
        Set<Class<?>> exceptions = result.test.getDeclaredExceptions();
        if (!exceptions.isEmpty()) {
           for (Class<?> exception : exceptions) {
              visitor.getClassName(exception);
           }
        }
         */

        // Also include thrown exceptions
        for (Throwable t : result.getAllThrownExceptions()) {
            visitor.getClassName(t.getClass());
        }

        imports.addAll(visitor.getImports());
    }

    if (Properties.RESET_STANDARD_STREAMS) {
        imports.add(PrintStream.class);
        imports.add(DebugGraphics.class);
    }

    Set<String> import_names = new HashSet<String>();
    for (Class<?> imp : imports) {
        while (imp.isArray())
            imp = imp.getComponentType();
        if (imp.isPrimitive())
            continue;
        if (imp.getName().startsWith("java.lang")) {
            String name = imp.getName().replace("java.lang.", "");
            if (!name.contains("."))
                continue;
        }
        if (!imp.getName().contains("."))
            continue;
        // TODO: Check for anonymous type?
        if (imp.getName().contains("$"))
            //   import_names.add(imp.getName().substring(0, imp.getName().indexOf("$")));
            import_names.add(imp.getName().replace("$", "."));
        else
            import_names.add(imp.getName());
    }
    List<String> imports_sorted = new ArrayList<String>(import_names);

    // FIXME: I disagree - it should be covered by the below branches
    //we always need this one, due to for example logging setup

    if (Properties.REPLACE_CALLS || Properties.VIRTUAL_FS || Properties.RESET_STATIC_FIELDS
            || wasSecurityException || SystemInUtil.getInstance().hasBeenUsed()) {
        imports_sorted.add(org.junit.BeforeClass.class.getCanonicalName());
        imports_sorted.add(org.junit.Before.class.getCanonicalName());
        imports_sorted.add(org.junit.After.class.getCanonicalName());
    }

    if (wasSecurityException || shouldResetProperties(results)) {
        imports_sorted.add(org.junit.AfterClass.class.getCanonicalName());
    }

    if (Properties.VIRTUAL_FS) {
        imports_sorted.add(org.evosuite.runtime.EvoSuiteFile.class.getCanonicalName());
    }

    if (wasSecurityException) {
        //Add import info for EvoSuite classes used in the generated test suite
        imports_sorted.add(Sandbox.class.getCanonicalName());
        // imports_sorted.add(Properties.class.getCanonicalName());
        imports_sorted.add(Properties.SandboxMode.class.getCanonicalName());
        imports_sorted.add(java.util.concurrent.ExecutorService.class.getCanonicalName());
        imports_sorted.add(java.util.concurrent.Executors.class.getCanonicalName());
        imports_sorted.add(java.util.concurrent.Future.class.getCanonicalName());
        imports_sorted.add(java.util.concurrent.TimeUnit.class.getCanonicalName());

    }

    Collections.sort(imports_sorted);
    for (String imp : imports_sorted) {
        builder.append("import ");
        builder.append(imp);
        builder.append(";\n");
    }
    builder.append("\n");
    return builder.toString();
}

From source file:com.zenesis.qx.remote.RequestHandler.java

/**
 * Reads an array from JSON, where each value is of the listed in types; EG the first element
 * is class type[0], the second element is class type[1] etc
 * @param jp/*from ww w . jav a2 s . c  om*/
 * @param types
 * @return
 * @throws IOException
 */
private Object[] readArray(JsonParser jp, Class[] types) throws IOException {
    if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
        return null;

    ArrayList result = new ArrayList();
    for (int paramIndex = 0; jp.nextToken() != JsonToken.END_ARRAY; paramIndex++) {
        Class type = null;
        if (types != null && paramIndex < types.length)
            type = types[paramIndex];

        if (type != null && type.isArray()) {
            if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
                result.add(null);
            else if (jp.getCurrentToken() == JsonToken.START_ARRAY) {
                Object obj = readArray(jp, type.getComponentType());
                result.add(obj);
            } else
                throw new IllegalStateException("Expected array but found " + jp.getCurrentToken());

        } else if (type != null && Proxied.class.isAssignableFrom(type)) {
            Integer id = jp.readValueAs(Integer.class);
            if (id != null) {
                Proxied obj = getProxied(id);
                result.add(obj);
            } else
                result.add(null);

        } else if (type != null && Enum.class.isAssignableFrom(type)) {
            Object obj = jp.readValueAs(Object.class);
            if (obj != null) {
                String str = Helpers.camelCaseToEnum(obj.toString());
                obj = Enum.valueOf(type, str);
                result.add(obj);
            }
        } else {
            Object obj = jp.readValueAs(type != null ? type : Object.class);
            result.add(obj);
        }
    }
    return result.toArray(new Object[result.size()]);
}

From source file:org.apache.hadoop.hbase.security.access.HbaseObjectWritableFor96Migration.java

/**
 * Read a {@link Writable}, {@link String}, primitive type, or an array of
 * the preceding.//  w w w  .j av a  2s  . c o m
 * @param in
 * @param objectWritable
 * @param conf
 * @return the object
 * @throws IOException
 */
@SuppressWarnings("unchecked")
static Object readObject(DataInput in, HbaseObjectWritableFor96Migration objectWritable, Configuration conf)
        throws IOException {
    Class<?> declaredClass = CODE_TO_CLASS.get(WritableUtils.readVInt(in));
    Object instance;
    if (declaredClass.isPrimitive()) { // primitive types
        if (declaredClass == Boolean.TYPE) { // boolean
            instance = Boolean.valueOf(in.readBoolean());
        } else if (declaredClass == Character.TYPE) { // char
            instance = Character.valueOf(in.readChar());
        } else if (declaredClass == Byte.TYPE) { // byte
            instance = Byte.valueOf(in.readByte());
        } else if (declaredClass == Short.TYPE) { // short
            instance = Short.valueOf(in.readShort());
        } else if (declaredClass == Integer.TYPE) { // int
            instance = Integer.valueOf(in.readInt());
        } else if (declaredClass == Long.TYPE) { // long
            instance = Long.valueOf(in.readLong());
        } else if (declaredClass == Float.TYPE) { // float
            instance = Float.valueOf(in.readFloat());
        } else if (declaredClass == Double.TYPE) { // double
            instance = Double.valueOf(in.readDouble());
        } else if (declaredClass == Void.TYPE) { // void
            instance = null;
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declaredClass);
        }
    } else if (declaredClass.isArray()) { // array
        if (declaredClass.equals(byte[].class)) {
            instance = Bytes.readByteArray(in);
        } else {
            int length = in.readInt();
            instance = Array.newInstance(declaredClass.getComponentType(), length);
            for (int i = 0; i < length; i++) {
                Array.set(instance, i, readObject(in, conf));
            }
        }
    } else if (declaredClass.equals(Array.class)) { //an array not declared in CLASS_TO_CODE
        Class<?> componentType = readClass(conf, in);
        int length = in.readInt();
        instance = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Array.set(instance, i, readObject(in, conf));
        }
    } else if (List.class.isAssignableFrom(declaredClass)) { // List
        int length = in.readInt();
        instance = new ArrayList(length);
        for (int i = 0; i < length; i++) {
            ((ArrayList) instance).add(readObject(in, conf));
        }
    } else if (declaredClass == String.class) { // String
        instance = Text.readString(in);
    } else if (declaredClass.isEnum()) { // enum
        instance = Enum.valueOf((Class<? extends Enum>) declaredClass, Text.readString(in));
    } else if (declaredClass == Message.class) {
        String className = Text.readString(in);
        try {
            declaredClass = getClassByName(conf, className);
            instance = tryInstantiateProtobuf(declaredClass, in);
        } catch (ClassNotFoundException e) {
            LOG.error("Can't find class " + className, e);
            throw new IOException("Can't find class " + className, e);
        }
    } else if (Scan.class.isAssignableFrom(declaredClass)) {
        int length = in.readInt();
        byte[] scanBytes = new byte[length];
        in.readFully(scanBytes);
        ClientProtos.Scan.Builder scanProto = ClientProtos.Scan.newBuilder();
        instance = ProtobufUtil.toScan(scanProto.mergeFrom(scanBytes).build());
    } else { // Writable or Serializable
        Class instanceClass = null;
        int b = (byte) WritableUtils.readVInt(in);
        if (b == NOT_ENCODED) {
            String className = Text.readString(in);
            try {
                instanceClass = getClassByName(conf, className);
            } catch (ClassNotFoundException e) {
                LOG.error("Can't find class " + className, e);
                throw new IOException("Can't find class " + className, e);
            }
        } else {
            instanceClass = CODE_TO_CLASS.get(b);
        }
        if (Writable.class.isAssignableFrom(instanceClass)) {
            Writable writable = WritableFactories.newInstance(instanceClass, conf);
            try {
                writable.readFields(in);
            } catch (Exception e) {
                LOG.error("Error in readFields", e);
                throw new IOException("Error in readFields", e);
            }
            instance = writable;
            if (instanceClass == NullInstance.class) { // null
                declaredClass = ((NullInstance) instance).declaredClass;
                instance = null;
            }
        } else {
            int length = in.readInt();
            byte[] objectBytes = new byte[length];
            in.readFully(objectBytes);
            ByteArrayInputStream bis = null;
            ObjectInputStream ois = null;
            try {
                bis = new ByteArrayInputStream(objectBytes);
                ois = new ObjectInputStream(bis);
                instance = ois.readObject();
            } catch (ClassNotFoundException e) {
                LOG.error("Class not found when attempting to deserialize object", e);
                throw new IOException("Class not found when attempting to " + "deserialize object", e);
            } finally {
                if (bis != null)
                    bis.close();
                if (ois != null)
                    ois.close();
            }
        }
    }
    if (objectWritable != null) { // store values
        objectWritable.declaredClass = declaredClass;
        objectWritable.instance = instance;
    }
    return instance;
}

From source file:org.apache.axis.utils.JavaUtils.java

public static boolean isConvertable(Object obj, Class dest, boolean isEncoded) {
    Class src = null;

    if (obj != null) {
        if (obj instanceof Class) {
            src = (Class) obj;//www. j  ava2 s  .c o m
        } else {
            src = obj.getClass();
        }
    } else {
        if (!dest.isPrimitive())
            return true;
    }

    if (dest == null)
        return false;

    if (src != null) {
        // If we're directly assignable, we're good.
        if (dest.isAssignableFrom(src))
            return true;

        //Allow mapping of Map's to Map's
        if (java.util.Map.class.isAssignableFrom(dest) && java.util.Map.class.isAssignableFrom(src)) {
            return true;
        }

        // If it's a wrapping conversion, we're good.
        if (getWrapperClass(src) == dest)
            return true;
        if (getWrapperClass(dest) == src)
            return true;

        // If it's List -> Array or vice versa, we're good.
        if ((Collection.class.isAssignableFrom(src) || src.isArray())
                && (Collection.class.isAssignableFrom(dest) || dest.isArray())
                && (src.getComponentType() == Object.class || src.getComponentType() == null
                        || dest.getComponentType() == Object.class || dest.getComponentType() == null
                        || isConvertable(src.getComponentType(), dest.getComponentType())))
            return true;

        // If destination is an array, and src is a component, we're good
        // if we're not encoded!
        if (!isEncoded && dest.isArray() &&
        //                !dest.getComponentType().equals(Object.class) &&
                dest.getComponentType().isAssignableFrom(src))
            return true;

        if ((src == HexBinary.class && dest == byte[].class)
                || (src == byte[].class && dest == HexBinary.class))
            return true;

        // Allow mapping of Calendar to Date
        if (Calendar.class.isAssignableFrom(src) && dest == Date.class)
            return true;

        // Allow mapping of Date to Calendar
        if (Date.class.isAssignableFrom(src) && dest == Calendar.class)
            return true;

        // Allow mapping of Calendar to java.sql.Date
        if (Calendar.class.isAssignableFrom(src) && dest == java.sql.Date.class)
            return true;
    }

    Class destHeld = JavaUtils.getHolderValueType(dest);
    // Can always convert a null to an empty holder
    if (src == null)
        return (destHeld != null);

    if (destHeld != null) {
        if (destHeld.isAssignableFrom(src) || isConvertable(src, destHeld))
            return true;
    }

    // If it's holder -> held or held -> holder, we're good
    Class srcHeld = JavaUtils.getHolderValueType(src);
    if (srcHeld != null) {
        if (dest.isAssignableFrom(srcHeld) || isConvertable(srcHeld, dest))
            return true;
    }

    // If it's a MIME type mapping and we want a DataHandler,
    // then we're good.
    if (dest.getName().equals("javax.activation.DataHandler")) {
        String name = src.getName();
        if (src == String.class || src == java.awt.Image.class || src == OctetStream.class
                || name.equals("javax.mail.internet.MimeMultipart")
                || name.equals("javax.xml.transform.Source"))
            return true;
    }

    if (src.getName().equals("javax.activation.DataHandler")) {
        if (dest == byte[].class)
            return true;
        if (dest.isArray() && dest.getComponentType() == byte[].class)
            return true;
    }

    if (dest.getName().equals("javax.activation.DataHandler")) {
        if (src == Object[].class)
            return true;
        if (src.isArray() && src.getComponentType() == Object[].class)
            return true;
    }

    if (obj instanceof java.io.InputStream) {
        if (dest == OctetStream.class)
            return true;
    }

    if (src.isPrimitive()) {
        return isConvertable(getWrapperClass(src), dest);
    }

    // ArrayOfT -> T[] ? 
    if (dest.isArray()) {
        if (ArrayUtil.isConvertable(src, dest) == true)
            return true;
    }

    // T[] -> ArrayOfT ?
    if (src.isArray()) {
        if (ArrayUtil.isConvertable(src, dest) == true)
            return true;
    }

    return false;
}

From source file:com.jaspersoft.jasperserver.ws.axis2.RepositoryHelper.java

protected Object getMultiParameterValues(JRParameter parameter, Collection values) {
    Object parameterValue;//from w  w  w.  jav  a  2s .c  o  m
    Class parameterType = parameter.getValueClass();
    if (parameterType.equals(Object.class) || parameterType.equals(Collection.class)
            || parameterType.equals(Set.class) || parameterType.equals(List.class)) {
        Collection paramValues;
        if (parameterType.equals(List.class)) {
            //if the parameter type is list, use a list
            paramValues = new ArrayList(values.size());
        } else {
            //else use an ordered set
            paramValues = new ListOrderedSet();
        }

        Class componentType = parameter.getNestedType();
        for (Iterator it = values.iterator(); it.hasNext();) {
            Object val = (Object) it.next();
            Object paramValue;
            if (componentType == null || !(val instanceof String)) {
                //no conversion if no nested type set for the parameter
                paramValue = val;
            } else {
                paramValue = stringToValue((String) val, componentType);
            }
            paramValues.add(paramValue);
        }
        parameterValue = paramValues;
    } else if (parameterType.isArray()) {
        Class componentType = parameterType.getComponentType();
        parameterValue = Array.newInstance(componentType, values.size());
        int idx = 0;
        for (Iterator iter = values.iterator(); iter.hasNext(); ++idx) {
            Object val = iter.next();
            Object paramValue;
            if (val instanceof String) {
                paramValue = stringToValue((String) val, componentType);
            } else {
                paramValue = val;
            }
            Array.set(parameterValue, idx, paramValue);
        }
    } else {
        parameterValue = values;
    }
    return parameterValue;
}

From source file:org.cloudata.core.common.io.CObjectWritable.java

/** Read a {@link CWritable}, {@link String}, primitive type, or an array of
 * the preceding. *//* w  w w.jav  a 2  s .co  m*/
@SuppressWarnings("unchecked")
public static Object readObject(DataInput in, CObjectWritable objectWritable, CloudataConf conf,
        boolean arrayComponent, Class componentClass) throws IOException {
    String className;
    if (arrayComponent) {
        className = componentClass.getName();
    } else {
        className = CUTF8.readString(in);
        //SANGCHUL
        //   System.out.println("SANGCHUL] className:" + className);
    }

    Class<?> declaredClass = PRIMITIVE_NAMES.get(className);
    if (declaredClass == null) {
        try {
            declaredClass = conf.getClassByName(className);
        } catch (ClassNotFoundException e) {
            //SANGCHUL
            e.printStackTrace();
            throw new RuntimeException("readObject can't find class[className=" + className + "]", e);
        }
    }

    Object instance;

    if (declaredClass.isPrimitive()) { // primitive types

        if (declaredClass == Boolean.TYPE) { // boolean
            instance = Boolean.valueOf(in.readBoolean());
        } else if (declaredClass == Character.TYPE) { // char
            instance = Character.valueOf(in.readChar());
        } else if (declaredClass == Byte.TYPE) { // byte
            instance = Byte.valueOf(in.readByte());
        } else if (declaredClass == Short.TYPE) { // short
            instance = Short.valueOf(in.readShort());
        } else if (declaredClass == Integer.TYPE) { // int
            instance = Integer.valueOf(in.readInt());
        } else if (declaredClass == Long.TYPE) { // long
            instance = Long.valueOf(in.readLong());
        } else if (declaredClass == Float.TYPE) { // float
            instance = Float.valueOf(in.readFloat());
        } else if (declaredClass == Double.TYPE) { // double
            instance = Double.valueOf(in.readDouble());
        } else if (declaredClass == Void.TYPE) { // void
            instance = null;
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declaredClass);
        }

    } else if (declaredClass.isArray()) { // array
        //System.out.println("SANGCHUL] is array");
        int length = in.readInt();
        //System.out.println("SANGCHUL] array length : " + length);
        //System.out.println("Read:in.readInt():" + length);
        if (declaredClass.getComponentType() == Byte.TYPE) {
            byte[] bytes = new byte[length];
            in.readFully(bytes);
            instance = bytes;
        } else if (declaredClass.getComponentType() == ColumnValue.class) {
            instance = readColumnValue(in, conf, declaredClass, length);
        } else {
            Class componentType = declaredClass.getComponentType();

            // SANGCHUL
            //System.out.println("SANGCHUL] componentType : " + componentType.getName());

            instance = Array.newInstance(componentType, length);
            for (int i = 0; i < length; i++) {
                Object arrayComponentInstance = readObject(in, null, conf, !componentType.isArray(),
                        componentType);
                Array.set(instance, i, arrayComponentInstance);
                //Array.set(instance, i, readObject(in, conf));
            }
        }
    } else if (declaredClass == String.class) { // String
        instance = CUTF8.readString(in);
    } else if (declaredClass.isEnum()) { // enum
        instance = Enum.valueOf((Class<? extends Enum>) declaredClass, CUTF8.readString(in));
    } else if (declaredClass == ColumnValue.class) {
        //ColumnValue?  ?? ?? ?  ? ?.
        //? ?   ? ? ? ? . 
        Class instanceClass = null;
        try {
            short typeDiff = in.readShort();
            if (typeDiff == TYPE_DIFF) {
                instanceClass = conf.getClassByName(CUTF8.readString(in));
            } else {
                instanceClass = declaredClass;
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("readObject can't find class", e);
        }
        ColumnValue columnValue = new ColumnValue();
        columnValue.readFields(in);
        instance = columnValue;
    } else { // Writable

        Class instanceClass = null;
        try {
            short typeDiff = in.readShort();
            // SANGCHUL
            //System.out.println("SANGCHUL] typeDiff : " + typeDiff);
            //System.out.println("Read:in.readShort():" + typeDiff);
            if (typeDiff == TYPE_DIFF) {
                // SANGCHUL
                String classNameTemp = CUTF8.readString(in);
                //System.out.println("SANGCHUL] typeDiff : " + classNameTemp);
                instanceClass = conf.getClassByName(classNameTemp);
                //System.out.println("Read:UTF8.readString(in):" + instanceClass.getClass());
            } else {
                instanceClass = declaredClass;
            }
        } catch (ClassNotFoundException e) {

            // SANGCHUL
            e.printStackTrace();
            throw new RuntimeException("readObject can't find class", e);
        }

        CWritable writable = CWritableFactories.newInstance(instanceClass, conf);
        writable.readFields(in);
        //System.out.println("Read:writable.readFields(in)");
        instance = writable;

        if (instanceClass == NullInstance.class) { // null
            declaredClass = ((NullInstance) instance).declaredClass;
            instance = null;
        }
    }

    if (objectWritable != null) { // store values
        objectWritable.declaredClass = declaredClass;
        objectWritable.instance = instance;
    }

    return instance;
}