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.medallia.spider.api.DynamicInputImpl.java

/**
 * Method used to parse values for the methods declared in {@link Input}.
 *//*  w w  w  .  j a  v  a 2  s  .  co  m*/
public <X> X getInput(String name, Class<X> type, AnnotatedElement anno) {
    // Special case for file uploads
    if (type.isAssignableFrom(UploadedFile.class))
        return type.cast(fileUploads.get(name));

    // Also support just getting the bytes from a file without the name
    if (type.isArray() && type.getComponentType() == Byte.TYPE) {
        UploadedFile uploadedFile = fileUploads.get(name);
        return uploadedFile != null ? type.cast(uploadedFile.getBytes()) : null;
    }

    if (type.isArray() && anno.isAnnotationPresent(Input.MultiValued.class)) {
        // return type is an array; grab all
        Object o = inputParams.get(name);
        return type.cast(parseMultiValue(type, o, anno));
    }

    String v = Strings.extract(inputParams.get(name));

    // boolean is used for checkboxes, and false is encoded as a missing value
    if (type == Boolean.class || type == Boolean.TYPE) {
        @SuppressWarnings("unchecked")
        X x = (X) Boolean.valueOf(v != null && !"false".equalsIgnoreCase(v));
        return x;
    }

    // the remaining types have proper null values
    if (v == null)
        return null;

    return cast(parseSingleValue(type, v, anno, inputArgParsers));
}

From source file:ome.util.ModelMapper.java

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

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

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

        if (currentType.isArray()) {

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

        } else {
            targetType = findClass(currentType);

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

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

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

From source file:org.apache.axis2.description.java2wsdl.DocLitBareSchemaGenerator.java

private QName generateSchemaForType(XmlSchemaSequence sequence, Class<?> type, String partName)
        throws Exception {

    boolean isArrayType = false;
    if (type != null) {
        isArrayType = type.isArray();//from www .  j  av  a 2s  .c  om
    }
    if (isArrayType) {
        type = type.getComponentType();
    }
    if (AxisFault.class.getName().equals(type)) {
        return null;
    }
    String classTypeName;
    if (type == null) {
        classTypeName = "java.lang.Object";
    } else {
        classTypeName = type.getName();
    }
    if (isArrayType && "byte".equals(classTypeName)) {
        classTypeName = "base64Binary";
        isArrayType = false;
    }
    if (isDataHandler(type)) {
        classTypeName = "base64Binary";
    }
    QName schemaTypeName = typeTable.getSimpleSchemaTypeName(classTypeName);
    if (schemaTypeName == null && type != null) {
        schemaTypeName = generateSchema(type);
        addContentToMethodSchemaType(sequence, schemaTypeName, partName, isArrayType);
        String schemaNamespace = resolveSchemaNamespace(getQualifiedName(type.getPackage()));
        addImport(getXmlSchema(schemaNamespace), schemaTypeName);
        if (sequence == null) {
            generateSchemaForSingleElement(schemaTypeName, partName, isArrayType);
        }
    } else {
        if (sequence == null) {
            generateSchemaForSingleElement(schemaTypeName, partName, isArrayType);
        } else {
            addContentToMethodSchemaType(sequence, schemaTypeName, partName, isArrayType);
        }
    }
    addImport(getXmlSchema(schemaTargetNameSpace), schemaTypeName);
    return schemaTypeName;
}

From source file:org.debux.webmotion.server.handler.ExecutorParametersConvertorHandler.java

protected Object convert(List<ParameterTree> parameterTrees, Class<?> type, Type genericType) throws Exception {
    Object result = null;//from  w w  w  .ja v  a 2s  .co m

    if (type.isArray()) {
        Class<?> componentType = type.getComponentType();

        Object[] tabConverted = (Object[]) Array.newInstance(componentType, parameterTrees.size());

        int index = 0;
        for (ParameterTree parameterTree : parameterTrees) {
            Object objectConverted = convert(parameterTree, componentType, null);
            tabConverted[index] = objectConverted;
            index++;
        }

        result = tabConverted;

    } else if (Collection.class.isAssignableFrom(type)) {

        Collection instance;
        if (type.isInterface()) {
            if (List.class.isAssignableFrom(type)) {
                instance = new ArrayList();

            } else if (Set.class.isAssignableFrom(type)) {
                instance = new HashSet();

            } else if (SortedSet.class.isAssignableFrom(type)) {
                instance = new TreeSet();

            } else {
                instance = new ArrayList();
            }
        } else {
            instance = (Collection) type.newInstance();
        }

        Class convertType = String.class;
        if (genericType != null && genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            convertType = (Class) parameterizedType.getActualTypeArguments()[0];
        }

        for (ParameterTree parameterTree : parameterTrees) {
            Object converted = convert(parameterTree, convertType, null);
            instance.add(converted);
        }

        result = instance;
    }

    return result;
}

From source file:org.apache.shindig.social.core.util.BeanJsonLibConverter.java

/**
 * Convert the json string into a pojo based on the supplied root class.
 * @param string the json string/*from   w  ww. j a  v a  2  s .co  m*/
 * @param rootBeanClass the root class of the bean
 * @param <T> The typep of the pojo to be returned
 * @return A pojo of the same type as the rootBeanClass
 */
@SuppressWarnings("unchecked")
public <T> T convertToObject(String string, final Class<T> rootBeanClass) {

    if ("".equals(string)) {
        string = "{}";
    }
    if (string.startsWith("[")) {
        JSONArray jsonArray = JSONArray.fromObject(string, jsonConfig);
        if (debugMode) {
            JsonLibConverterUtils.dumpJsonArray(jsonArray, " ");
        }

        if (rootBeanClass.isArray()) {
            Class<?> componentType = rootBeanClass.getComponentType();
            Object rootObject = injector.getInstance(componentType);
            List<?> o = JSONArray.toList(jsonArray, rootObject, jsonConfig);
            Object[] result = (Object[]) Array.newInstance(componentType, o.size());
            for (int i = 0; i < o.size(); i++) {
                result[i] = o.get(i);
            }
            return (T) result;

        } else {
            T rootObject = injector.getInstance(rootBeanClass);
            Object o = JSONArray.toArray(jsonArray, rootObject, jsonConfig);
            return (T) o;
        }
    } else {
        JSONObject jsonObject = JSONObject.fromObject(string, jsonConfig);

        if (debugMode) {
            JsonLibConverterUtils.dumpJsonObject(jsonObject, " ");
        }

        T rootObject = injector.getInstance(rootBeanClass);
        Object o = JSONObject.toBean(jsonObject, rootObject, jsonConfig);
        return (T) o;

    }
}

From source file:com.datos.vfs.util.DelegatingFileSystemOptionsBuilder.java

/**
 * tries to convert the value and pass it to the given method
 *//*from   w  w w.  ja va 2  s  . co m*/
private boolean convertValuesAndInvoke(final Method configSetter, final Context ctx)
        throws FileSystemException {
    final Class<?>[] parameters = configSetter.getParameterTypes();
    if (parameters.length < 2) {
        return false;
    }
    if (!parameters[0].isAssignableFrom(FileSystemOptions.class)) {
        return false;
    }

    final Class<?> valueParameter = parameters[1];
    Class<?> type;
    if (valueParameter.isArray()) {
        type = valueParameter.getComponentType();
    } else {
        if (ctx.values.length > 1) {
            return false;
        }

        type = valueParameter;
    }

    if (type.isPrimitive()) {
        final Class<?> objectType = PRIMATIVE_TO_OBJECT.get(type.getName());
        if (objectType == null) {
            log.warn(Messages.getString("vfs.provider/config-unexpected-primitive.error", type.getName()));
            return false;
        }
        type = objectType;
    }

    final Class<? extends Object> valueClass = ctx.values[0].getClass();
    if (type.isAssignableFrom(valueClass)) {
        // can set value directly
        invokeSetter(valueParameter, ctx, configSetter, ctx.values);
        return true;
    }
    if (valueClass != String.class) {
        log.warn(Messages.getString("vfs.provider/config-unexpected-value-class.error", valueClass.getName(),
                ctx.scheme, ctx.name));
        return false;
    }

    final Object convertedValues = Array.newInstance(type, ctx.values.length);

    Constructor<?> valueConstructor;
    try {
        valueConstructor = type.getConstructor(STRING_PARAM);
    } catch (final NoSuchMethodException e) {
        valueConstructor = null;
    }
    if (valueConstructor != null) {
        // can convert using constructor
        for (int iterValues = 0; iterValues < ctx.values.length; iterValues++) {
            try {
                Array.set(convertedValues, iterValues,
                        valueConstructor.newInstance(new Object[] { ctx.values[iterValues] }));
            } catch (final InstantiationException e) {
                throw new FileSystemException(e);
            } catch (final IllegalAccessException e) {
                throw new FileSystemException(e);
            } catch (final InvocationTargetException e) {
                throw new FileSystemException(e);
            }
        }

        invokeSetter(valueParameter, ctx, configSetter, convertedValues);
        return true;
    }

    Method valueFactory;
    try {
        valueFactory = type.getMethod("valueOf", STRING_PARAM);
        if (!Modifier.isStatic(valueFactory.getModifiers())) {
            valueFactory = null;
        }
    } catch (final NoSuchMethodException e) {
        valueFactory = null;
    }

    if (valueFactory != null) {
        // can convert using factory method (valueOf)
        for (int iterValues = 0; iterValues < ctx.values.length; iterValues++) {
            try {
                Array.set(convertedValues, iterValues,
                        valueFactory.invoke(null, new Object[] { ctx.values[iterValues] }));
            } catch (final IllegalAccessException e) {
                throw new FileSystemException(e);
            } catch (final InvocationTargetException e) {
                throw new FileSystemException(e);
            }
        }

        invokeSetter(valueParameter, ctx, configSetter, convertedValues);
        return true;
    }

    return false;
}

From source file:com.google.feedserver.util.BeanUtil.java

/**
 * Applies a collection of properties to a JavaBean. Converts String and
 * String[] values to correct property types
 * //ww w .j  a va 2s  .c o m
 * @param properties A map of the properties to set on the JavaBean
 * @param bean The JavaBean to set the properties on
 */
public void convertPropertiesToBean(Map<String, Object> properties, Object bean) throws IntrospectionException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException, ParseException {
    BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
    for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) {
        String name = p.getName();
        Object value = properties.get(name);
        Method reader = p.getReadMethod();
        Method writer = p.getWriteMethod();
        // we only care about "complete" properties
        if (reader != null && writer != null && value != null) {
            Class<?> propertyType = writer.getParameterTypes()[0];
            if (isBean(propertyType)) {
                // this is a bean
                if (propertyType.isArray()) {
                    propertyType = propertyType.getComponentType();
                    Object beanArray = Array.newInstance(propertyType, 1);

                    if (value.getClass().isArray()) {
                        Object[] valueArrary = (Object[]) value;
                        int length = valueArrary.length;
                        beanArray = Array.newInstance(propertyType, length);
                        for (int index = 0; index < valueArrary.length; ++index) {
                            Object valueObject = valueArrary[index];
                            fillBeanInArray(propertyType, beanArray, index, valueObject);
                        }
                    } else {
                        fillBeanInArray(propertyType, beanArray, 0, value);
                    }
                    value = beanArray;
                } else if (propertyType == Timestamp.class) {
                    value = new Timestamp(TIMESTAMP_FORMAT.parse((String) value).getTime());
                } else {
                    Object beanObject = createBeanObject(propertyType, value);
                    value = beanObject;
                }
            } else {
                Class<?> valueType = value.getClass();
                if (!propertyType.isAssignableFrom(valueType)) {
                    // convert string input values to property type
                    try {
                        if (valueType == String.class) {
                            value = ConvertUtils.convert((String) value, propertyType);
                        } else if (valueType == String[].class) {
                            value = ConvertUtils.convert((String[]) value, propertyType);
                        } else if (valueType == Object[].class) {
                            // best effort conversion
                            Object[] objectValues = (Object[]) value;
                            String[] stringValues = new String[objectValues.length];
                            for (int i = 0; i < objectValues.length; i++) {
                                stringValues[i] = objectValues[i] == null ? null : objectValues[i].toString();
                            }
                            value = ConvertUtils.convert(stringValues, propertyType);
                        } else {
                        }
                    } catch (ConversionException e) {
                        throw new IllegalArgumentException(
                                "Conversion failed for " + "property '" + name + "' with value '" + value + "'",
                                e);
                    }
                }
            }
            // We only write values that are present in the map. This allows
            // defaults or previously set values in the bean to be retained.
            writer.invoke(bean, value);
        }
    }
}

From source file:org.apache.click.util.RequestTypeConverter.java

/**
 * Return the converted value for the given value object and target type.
 *
 * @param value the value object to convert
 * @param toType the target class type to convert the value to
 * @return a converted value into the specified type
 *//*from  w w w  .  j a  va 2s  .  c o m*/
protected Object convertValue(Object value, Class<?> toType) {
    Object result = null;

    if (value != null) {

        // If array -> array then convert components of array individually
        if (value.getClass().isArray() && toType.isArray()) {
            Class<?> componentType = toType.getComponentType();

            result = Array.newInstance(componentType, Array.getLength(value));

            for (int i = 0, icount = Array.getLength(value); i < icount; i++) {
                Array.set(result, i, convertValue(Array.get(value, i), componentType));
            }

        } else {
            if ((toType == Integer.class) || (toType == Integer.TYPE)) {
                result = Integer.valueOf((int) OgnlOps.longValue(value));

            } else if ((toType == Double.class) || (toType == Double.TYPE)) {
                result = new Double(OgnlOps.doubleValue(value));

            } else if ((toType == Boolean.class) || (toType == Boolean.TYPE)) {
                result = Boolean.valueOf(value.toString());

            } else if ((toType == Byte.class) || (toType == Byte.TYPE)) {
                result = Byte.valueOf((byte) OgnlOps.longValue(value));

            } else if ((toType == Character.class) || (toType == Character.TYPE)) {
                result = Character.valueOf((char) OgnlOps.longValue(value));

            } else if ((toType == Short.class) || (toType == Short.TYPE)) {
                result = Short.valueOf((short) OgnlOps.longValue(value));

            } else if ((toType == Long.class) || (toType == Long.TYPE)) {
                result = Long.valueOf(OgnlOps.longValue(value));

            } else if ((toType == Float.class) || (toType == Float.TYPE)) {
                result = new Float(OgnlOps.doubleValue(value));

            } else if (toType == BigInteger.class) {
                result = OgnlOps.bigIntValue(value);

            } else if (toType == BigDecimal.class) {
                result = bigDecValue(value);

            } else if (toType == String.class) {
                result = OgnlOps.stringValue(value);

            } else if (toType == java.util.Date.class) {
                long time = getTimeFromDateString(value.toString());
                if (time > Long.MIN_VALUE) {
                    result = new java.util.Date(time);
                }

            } else if (toType == java.sql.Date.class) {
                long time = getTimeFromDateString(value.toString());
                if (time > Long.MIN_VALUE) {
                    result = new java.sql.Date(time);
                }

            } else if (toType == java.sql.Time.class) {
                long time = getTimeFromDateString(value.toString());
                if (time > Long.MIN_VALUE) {
                    result = new java.sql.Time(time);
                }

            } else if (toType == java.sql.Timestamp.class) {
                long time = getTimeFromDateString(value.toString());
                if (time > Long.MIN_VALUE) {
                    result = new java.sql.Timestamp(time);
                }
            }
        }

    } else {
        if (toType.isPrimitive()) {
            result = OgnlRuntime.getPrimitiveDefaultValue(toType);
        }
    }
    return result;
}

From source file:org.commonreality.object.delta.DeltaTracker.java

@SuppressWarnings("unchecked")
private boolean isActualChange(String keyName, Object newValue) {
    if (newValue != null) {
        if (!_actualObject.hasProperty(keyName))
            return true;

        Object oldValue = null;// ww w .jav a 2 s  . co  m

        // if (checkOnlyActualObject)
        oldValue = _actualObject.getProperty(keyName);
        // else
        // oldValue = getProperty(keyName);

        if (newValue == oldValue)
            return false;

        if (newValue.equals(oldValue))
            return false;

        /*
         * now we need to see if they are arrays
         */
        Class newClass = newValue.getClass();
        Class oldClass = Object.class;
        if (oldValue != null)
            oldClass = oldValue.getClass();
        if (newClass != oldClass)
            return true;

        if (newClass.isArray() && oldClass.isArray()) {
            if (newClass.getComponentType() != oldClass.getComponentType())
                return true;

            /*
             * now we have to check the elements
             */
            if (newClass.getComponentType().isPrimitive()) {
                boolean rtn = true;
                if (newClass.getComponentType() == Float.TYPE)
                    rtn = compareFloats((float[]) newValue, (float[]) oldValue);
                else if (newClass.getComponentType() == Double.TYPE)
                    rtn = compareDoubles((double[]) newValue, (double[]) oldValue);
                else if (newClass.getComponentType() == Boolean.TYPE)
                    rtn = compareBooleans((boolean[]) newValue, (boolean[]) oldValue);
                else if (newClass.getComponentType() == Integer.TYPE)
                    rtn = compareInts((int[]) newValue, (int[]) oldValue);
                else if (LOGGER.isWarnEnabled())
                    LOGGER.warn("Cannot compare arrays of " + newClass.getComponentType().getName());
                return rtn;
            } else {
                Object[] newArray = (Object[]) newValue;
                Object[] oldArray = (Object[]) oldValue;

                if (newArray.length != oldArray.length)
                    return true;

                for (int i = 0; i < newArray.length; i++)
                    if (!newArray[i].equals(oldArray[i]))
                        return true;

                return false;
            }

        }
    } else // unsetting the property
    if (_actualObject.hasProperty(keyName))
        return true;

    return true;
}

From source file:org.eclipse.wb.internal.core.databinding.ui.editor.contentproviders.ChooseClassUiContentProvider.java

/**
 * This method calculate state and sets or clear error message. Subclasses maybe override this
 * method for observe special states./*from   w w  w . j a  va  2  s .c  o  m*/
 */
protected void calculateFinish() {
    String className = getClassName();
    // route events
    if (m_router != null) {
        m_router.handle();
    }
    // check state
    if (className.length() == 0) {
        // empty class
        setErrorMessage(m_configuration.getEmptyClassErrorMessage());
    } else {
        // check clear of default value (maybe not class)
        if (m_configuration.isDefaultString(className) || className.equals(m_configuration.getClearValue())
                || ArrayUtils.indexOf(m_configuration.getDefaultValues(), className) != -1) {
            setErrorMessage(null);
            return;
        }
        // check load class
        Class<?>[][] constructorsParameters = m_configuration.getConstructorsParameters();
        String errorMessagePrefix = m_configuration.getErrorMessagePrefix();
        //
        boolean noConstructor = false;
        try {
            Class<?> testClass = loadClass(className);
            // check permissions
            int modifiers = testClass.getModifiers();
            if (!Modifier.isPublic(modifiers)) {
                setErrorMessage(errorMessagePrefix + Messages.ChooseClassUiContentProvider_validateNotPublic);
                return;
            }
            if (!m_configuration.isChooseInterfaces() && Modifier.isAbstract(modifiers)) {
                setErrorMessage(errorMessagePrefix + Messages.ChooseClassUiContentProvider_validateAbstract);
                return;
            }
            // check constructor
            if (m_checkClasses) {
                m_checkClasses = false;
                if (constructorsParameters != null) {
                    for (int i = 0; i < constructorsParameters.length; i++) {
                        Class<?>[] constructorParameters = constructorsParameters[i];
                        for (int j = 0; j < constructorParameters.length; j++) {
                            Class<?> constructorParameterClass = constructorParameters[j];
                            if (constructorParameterClass.isArray()) {
                                String parameterClassName = constructorParameterClass.getComponentType()
                                        .getName();
                                if (parameterClassName.startsWith("org.eclipse")) {
                                    constructorParameters[j] = Array
                                            .newInstance(loadClass(parameterClassName), new int[1]).getClass();
                                }
                            } else {
                                String parameterClassName = constructorParameterClass.getName();
                                if (parameterClassName.startsWith("org.eclipse")) {
                                    constructorParameters[j] = loadClass(parameterClassName);
                                }
                            }
                        }
                    }
                }
            }
            if (constructorsParameters != null) {
                noConstructor = true;
                for (int i = 0; i < constructorsParameters.length; i++) {
                    try {
                        testClass.getConstructor(constructorsParameters[i]);
                        noConstructor = false;
                        break;
                    } catch (SecurityException e) {
                    } catch (NoSuchMethodException e) {
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            setErrorMessage(errorMessagePrefix + Messages.ChooseClassUiContentProvider_validateNotExist);
            return;
        }
        // prepare error message for constructor
        if (noConstructor) {
            StringBuffer parameters = new StringBuffer(errorMessagePrefix);
            parameters.append(Messages.ChooseClassUiContentProvider_validatePublicConstructor);
            for (int i = 0; i < constructorsParameters.length; i++) {
                Class<?>[] constructorParameters = constructorsParameters[i];
                if (i > 0) {
                    parameters.append(" ");
                }
                parameters.append(ClassUtils.getShortClassName(className));
                parameters.append("(");
                for (int j = 0; j < constructorParameters.length; j++) {
                    if (j > 0) {
                        parameters.append(", ");
                    }
                    parameters.append(ClassUtils.getShortClassName(constructorParameters[j]));
                }
                parameters.append(")");
            }
            parameters.append(".");
            setErrorMessage(parameters.toString());
        } else {
            setErrorMessage(null);
        }
    }
}