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:org.evosuite.testcase.ImportsTestCodeVisitor.java

/**
 * <p>//from   ww  w.  j ava  2  s . co m
 * getClassName
 * </p>
 *
 * @param clazz
 *            a {@link Class} object.
 * @return a {@link String} object.
 */
public String getClassName(Class<?> clazz) {
    if (classNames.containsKey(clazz))
        return classNames.get(clazz);

    if (clazz.isArray()) {
        return getClassName(clazz.getComponentType()) + "[]";
    }

    GenericClass c = new GenericClass(clazz);
    String name = c.getSimpleName();
    if (classNames.values().contains(name)) {
        name = clazz.getCanonicalName();
    } else {
        /*
         * If e.g. there is a foo.bar.IllegalStateException with
         * foo.bar being the SUT package, then we need to use the
         * full package name for java.lang.IllegalStateException
         */
        String fullName = Properties.CLASS_PREFIX + "." + name;
        if (!fullName.equals(clazz.getCanonicalName())) {
            try {
                if (ResourceList.getInstance(TestGenerationContext.getInstance().getClassLoaderForSUT())
                        .hasClass(fullName)) {
                    name = clazz.getCanonicalName();
                }
            } catch (IllegalArgumentException e) {
                // If the classpath is not correct, then we just don't check
                // because that cannot happen in regular EvoSuite use, only
                // from test cases
            }
        }
    }
    // Ensure outer classes are imported as well
    Class<?> outerClass = clazz.getEnclosingClass();
    if (outerClass != null) {
        String enclosingName = getClassName(outerClass);
        String simpleOuterName = outerClass.getSimpleName();
        if (simpleOuterName.equals(enclosingName)) {
            name = enclosingName + name.substring(simpleOuterName.length());
        } else {
            name = enclosingName + name.substring(name.lastIndexOf(simpleOuterName) + simpleOuterName.length());
        }
    }

    Class<?> declaringClass = clazz.getDeclaringClass();
    if (declaringClass != null) {
        getClassName(declaringClass);
    }

    // We can't use "Test" because of JUnit
    if (name.equals("Test")) {
        name = clazz.getCanonicalName();
    }
    classNames.put(clazz, name);

    return name;
}

From source file:org.hdiv.webflow.mvc.servlet.ServletMvcViewHDIV.java

private Object getEmptyValue(Class fieldType) {
    if (fieldType != null && boolean.class.equals(fieldType) || Boolean.class.equals(fieldType)) {
        // Special handling of boolean property.
        return Boolean.FALSE;
    } else if (fieldType != null && fieldType.isArray()) {
        // Special handling of array property.
        return Array.newInstance(fieldType.getComponentType(), 0);
    } else {// www .  ja va 2 s  .c o m
        // Default value: try null.
        return null;
    }
}

From source file:java2typescript.jackson.module.StaticFieldExporter.java

private Value constructValue(Module module, Class<?> type, Object rawValue)
        throws IllegalArgumentException, IllegalAccessException {
    if (type == boolean.class) {
        return new Value(BooleanType.getInstance(), rawValue);
    } else if (type == int.class) {
        return new Value(NumberType.getInstance(), rawValue);
    } else if (type == double.class) {
        return new Value(NumberType.getInstance(), rawValue);
    } else if (type == String.class) {
        return new Value(StringType.getInstance(), "'" + (String) rawValue + "'");
    } else if (type.isEnum()) {
        final EnumType enumType = tsJsonFormatVisitorWrapper.parseEnumOrGetFromCache(module,
                SimpleType.construct(type));
        return new Value(enumType, enumType.getName() + "." + rawValue);
    } else if (type.isArray()) {
        final Class<?> componentType = type.getComponentType();
        final Object[] array;
        if (componentType == boolean.class) {
            boolean[] tmpArray = (boolean[]) rawValue;
            array = new Boolean[tmpArray.length];
            for (int i = 0; i < array.length; i++) {
                array[i] = Boolean.valueOf(tmpArray[i]);
            }/*from   www  .  j a v  a 2s.com*/
        } else if (componentType == int.class) {
            int[] tmpArray = (int[]) rawValue;
            array = new Integer[tmpArray.length];
            for (int i = 0; i < array.length; i++) {
                array[i] = Integer.valueOf(tmpArray[i]);
            }
        } else if (componentType == double.class) {
            double[] tmpArray = (double[]) rawValue;
            array = new Double[tmpArray.length];
            for (int i = 0; i < array.length; i++) {
                array[i] = Double.valueOf(tmpArray[i]);
            }
        } else {
            array = (Object[]) rawValue;
        }
        final StringBuilder arrayValues = new StringBuilder();
        arrayValues.append("[ ");
        for (int i = 0; i < array.length; i++) {
            arrayValues.append(constructValue(module, componentType, array[i]).getValue());
            if (i < array.length - 1) {
                arrayValues.append(", ");
            }
        }
        arrayValues.append(" ]");
        return new Value(new ArrayType(typeScriptTypeFromJavaType(module, componentType)),
                arrayValues.toString());
    }
    return null;
}

From source file:com.flexive.faces.renderer.FxSelectRenderer.java

/**
 * Convert select many values to given array class
 *
 * @param context      faces context/*from   ww w  .  j  ava2 s  . c o  m*/
 * @param uiSelectMany select many component
 * @param arrayClass   the array class
 * @param newValues    new values to convert
 * @return converted values
 * @throws ConverterException on errors
 */
protected Object convertSelectManyValues(FacesContext context, UISelectMany uiSelectMany, Class arrayClass,
        String[] newValues) throws ConverterException {

    Object result;
    Converter converter;
    int len = (null != newValues ? newValues.length : 0);

    Class elementType = arrayClass.getComponentType();

    // Optimization: If the elementType is String, we don't need
    // conversion.  Just return newValues.
    if (elementType.equals(String.class))
        return newValues;

    try {
        result = Array.newInstance(elementType, len);
    } catch (Exception e) {
        throw new ConverterException(e);
    }

    // bail out now if we have no new values, returning our
    // oh-so-useful zero-length array.
    if (null == newValues)
        return result;

    // obtain a converter.

    // attached converter takes priority
    if (null == (converter = uiSelectMany.getConverter())) {
        // Otherwise, look for a by-type converter
        if (null == (converter = FxJsfComponentUtils.getConverterForClass(elementType, context))) {
            // if that fails, and the attached values are of Object type,
            // we don't need conversion.
            if (elementType.equals(Object.class))
                return newValues;
            StringBuffer valueStr = new StringBuffer();
            for (int i = 0; i < len; i++) {
                if (i == 0)
                    valueStr.append(newValues[i]);
                else
                    valueStr.append(' ').append(newValues[i]);
            }
            throw new ConverterException("Could not get a converter for " + String.valueOf(valueStr));
        }
    }

    if (elementType.isPrimitive()) {
        for (int i = 0; i < len; i++) {
            if (elementType.equals(Boolean.TYPE)) {
                Array.setBoolean(result, i,
                        ((Boolean) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Byte.TYPE)) {
                Array.setByte(result, i, ((Byte) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Double.TYPE)) {
                Array.setDouble(result, i,
                        ((Double) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Float.TYPE)) {
                Array.setFloat(result, i, ((Float) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Integer.TYPE)) {
                Array.setInt(result, i, ((Integer) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Character.TYPE)) {
                Array.setChar(result, i,
                        ((Character) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Short.TYPE)) {
                Array.setShort(result, i, ((Short) converter.getAsObject(context, uiSelectMany, newValues[i])));
            } else if (elementType.equals(Long.TYPE)) {
                Array.setLong(result, i, ((Long) converter.getAsObject(context, uiSelectMany, newValues[i])));
            }
        }
    } else {
        for (int i = 0; i < len; i++)
            Array.set(result, i, converter.getAsObject(context, uiSelectMany, newValues[i]));
    }
    return result;
}

From source file:com.github.dozermapper.core.util.ReflectionUtils.java

public static DeepHierarchyElement[] getDeepFieldHierarchy(Class<?> parentClass, String field,
        HintContainer deepIndexHintContainer) {
    if (!MappingUtils.isDeepMapping(field)) {
        MappingUtils.throwMappingException("Field does not contain deep field delimitor");
    }//w  w  w . j a v  a 2 s .c o  m

    StringTokenizer toks = new StringTokenizer(field, DozerConstants.DEEP_FIELD_DELIMITER);
    Class<?> latestClass = parentClass;
    DeepHierarchyElement[] hierarchy = new DeepHierarchyElement[toks.countTokens()];
    int index = 0;
    int hintIndex = 0;
    while (toks.hasMoreTokens()) {
        String aFieldName = toks.nextToken();
        String theFieldName = aFieldName;
        int collectionIndex = -1;

        if (aFieldName.contains("[")) {
            theFieldName = aFieldName.substring(0, aFieldName.indexOf("["));
            collectionIndex = Integer
                    .parseInt(aFieldName.substring(aFieldName.indexOf("[") + 1, aFieldName.indexOf("]")));
        }

        PropertyDescriptor propDescriptor = findPropertyDescriptor(latestClass, theFieldName,
                deepIndexHintContainer);
        DeepHierarchyElement r = new DeepHierarchyElement(propDescriptor, collectionIndex);

        if (propDescriptor == null) {
            MappingUtils
                    .throwMappingException("Exception occurred determining deep field hierarchy for Class --> "
                            + parentClass.getName() + ", Field --> " + field
                            + ".  Unable to determine property descriptor for Class --> "
                            + latestClass.getName() + ", Field Name: " + aFieldName);
        }

        latestClass = propDescriptor.getPropertyType();
        if (toks.hasMoreTokens()) {
            if (latestClass.isArray()) {
                latestClass = latestClass.getComponentType();
            } else if (Collection.class.isAssignableFrom(latestClass)) {
                Class<?> genericType = determineGenericsType(parentClass.getClass(), propDescriptor);

                if (genericType == null && deepIndexHintContainer == null) {
                    MappingUtils.throwMappingException(
                            "Hint(s) or Generics not specified.  Hint(s) or Generics must be specified for deep mapping with indexed field(s). "
                                    + "Exception occurred determining deep field hierarchy for Class --> "
                                    + parentClass.getName() + ", Field --> " + field
                                    + ".  Unable to determine property descriptor for Class --> "
                                    + latestClass.getName() + ", Field Name: " + aFieldName);
                }

                if (genericType != null) {
                    latestClass = genericType;
                } else {
                    latestClass = deepIndexHintContainer.getHint(hintIndex);
                    hintIndex += 1;
                }
            }
        }
        hierarchy[index++] = r;
    }

    return hierarchy;
}

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

/**
 * Looks up an instance of a service and creates one if necessary.
 *
 * @param   session             the current session (for storing
 *                              instances).
 * @param   serviceClassName    the fully qualified name of the class
 *                              to instantiate.
 * @param   name                the name to use for the instance.
 * @param   requiredType        The type the service must have. May be
 *                              null. //ww  w  . j a v  a2  s .  co  m
 */

public synchronized Service getServiceInstance(HttpSession session, String serviceClassName, Object name,
        Class requiredType) throws ClassNotFoundException, IllegalAccessException, InstantiationException,
        InvocationTargetException, NoSuchMethodException {

    if (requiredType == null) {
        requiredType = Service.class;
    }

    String lookFor = serviceClassName;
    if (name != null) {
        lookFor += "/" + name;
    }
    Service inst = (Service) session.getAttribute(lookFor);
    if (inst == null) {
        Class clazz = Class.forName(serviceClassName);
        if (!requiredType.isAssignableFrom(clazz)) {
            throw new ClassCastException("The requested service class " + clazz.getName()
                    + " is not from the required type " + requiredType.getName() + "");
        }
        inst = (Service) clazz.newInstance();
        Class[] paramTypes = new Class[1];
        Object[] params = new Object[1];
        paramTypes[0] = Environment.class;
        Method method = MethodUtils.getMatchingAccessibleMethod(clazz, "setWebcomponentEnvironment",
                paramTypes);
        if (method == null) {
            method = MethodUtils.getMatchingAccessibleMethod(clazz, "setQooxdooEnvironment", paramTypes);
        }
        if (method != null) {
            params[0] = new Environment();
            method.invoke(inst, params);
        }
        if (name != null) {
            paramTypes[0] = String.class;
            method = MethodUtils.getMatchingAccessibleMethod(clazz, "setWebcomponentName", paramTypes);
            if (method != null) {
                params[0] = name;
                method.invoke(inst, params);
            }
        }
        session.setAttribute(lookFor, inst);

        // initialize the service properties
        ServletConfig servletConfig = getServletConfig();
        Enumeration initParamNames = servletConfig.getInitParameterNames();
        String initParamName;
        String initParamValue;
        int pos;
        String packageName;
        String propertyName;
        HashMap candidates = new HashMap();
        while (initParamNames.hasMoreElements()) {
            initParamName = (String) initParamNames.nextElement();
            pos = initParamName.lastIndexOf('.');
            if (pos == -1) {
                packageName = "";
                propertyName = initParamName;
            } else {
                packageName = initParamName.substring(0, pos);
                propertyName = initParamName.substring(pos + 1);
            }
            String candidateName;
            if (serviceClassName.startsWith(packageName)) {
                candidateName = (String) candidates.get(propertyName);
                if (candidateName == null) {
                    candidates.put(propertyName, initParamName);
                } else if (candidateName.length() < initParamName.length()) {
                    candidates.put(propertyName, initParamName);
                }
            }
        }
        Iterator candidatesIterator = candidates.keySet().iterator();
        Class propertyType;
        while (candidatesIterator.hasNext()) {
            propertyName = (String) candidatesIterator.next();
            initParamName = (String) candidates.get(propertyName);
            initParamValue = servletConfig.getInitParameter(initParamName);
            propertyType = PropertyUtils.getPropertyType(inst, propertyName);
            if (propertyType != null) {
                if (propertyType.getComponentType() == String.class) {
                    PropertyUtils.setSimpleProperty(inst, propertyName,
                            StringUtils.tokenize(initParamValue, ';'));
                } else {
                    try {
                        PropertyUtils.setSimpleProperty(inst, propertyName,
                                ConvertUtils.convert(initParamValue, propertyType));
                    } catch (Exception e) {
                        // try to instatiate a class of the supplied parameter
                        //System.out.println("***** setting '" + propertyName + "' to an instance of '" + initParamValue + "'");
                        PropertyUtils.setSimpleProperty(inst, propertyName,
                                getServiceInstance(session, initParamValue, null, null));
                    }
                }
            } else {
                //System.out.println("***** property '" + propertyName + "' not matched");
            }
        }

        // tell the instance that we're done
        paramTypes = new Class[0];
        method = MethodUtils.getMatchingAccessibleMethod(clazz, "webcomponentInit", paramTypes);
        if (method != null) {
            params = new Object[0];
            method.invoke(inst, params);
        }
    }
    return inst;
}

From source file:org.boris.xlloop.util.XLoperObjectConverter.java

/**
 * Creates a java object from an XLObject.
 * /*  w w  w  . java 2  s  .  c  o  m*/
 * @param obj.
 * @param hint.
 * 
 * @return Object.
 */
public Object createFrom(XLoper obj, Class hint, SessionContext sessionContext) {
    // If Excel passes a single value and the Java code expects an array,
    // try to convert based on the component type, and then create the
    // array.
    if (obj.type != XLoper.xlTypeMulti && hint.isArray()) {
        Object value = doTypeSwitch(obj, hint.getComponentType(), sessionContext);
        Object array = Array.newInstance(hint.getComponentType(), 1);
        Array.set(array, 0, value);
        return array;
    } else {
        return doTypeSwitch(obj, hint, sessionContext);
    }
}

From source file:com.spidertracks.datanucleus.convert.ByteConverterContext.java

/**
 * Determine the converter that should be used for this class. Will not
 * perform any caching on converters that are created, however it does check
 * the cache for existing definitions Creates converters with the following
 * order/*from   ww  w.j  av  a  2  s  .  co  m*/
 * 
 * <ol>
 * <li>ByteConverter from converter Mapping</li>
 * <li>ByteAware implementation</li>
 * <li>ObjectLongConverter which is cached</li>
 * <li>ObjectStringConverter which is cached</li>
 * <li>Serialization using the serializer which is cached</li>
 * </ol>
 * 
 * @param clazz
 * @return
 */
private ByteConverter determineConverter(Class<?> clazz) {

    // 1. If there is a converter for the specific class then use it.
    ByteConverter converter = converters.get(clazz);

    if (converter != null) {
        return converter;
    }

    // 2. If the class is an array then look inside of it and try using the inner class.
    if (clazz.isArray()) {
        final ByteConverter innerConverter = this.determineConverter(clazz.getComponentType());
        // It makes no sense to store an array of opaque objects so if the converter
        // is the serializerConverter then we won't bother looking in the array.
        if (innerConverter == this.serializerConverter) {
            return this.serializerConverter;
        }
        return new ArrayConverter(innerConverter, clazz.getComponentType());
    }

    if (ByteAware.class.isAssignableFrom(clazz)) {
        return new ByteAwareConverter(clazz);
    }

    ObjectLongConverter dnLongConverter = typeManager.getLongConverter(clazz);

    if (dnLongConverter != null) {
        return new ObjectLongWrapperConverter(dnLongConverter, this.longConverter);
    }

    ObjectStringConverter dnStringConverter = typeManager.getStringConverter(clazz);

    if (dnStringConverter != null) {
        return new ObjectStringWrapperConverter(dnStringConverter, this.stringConverter);
    }

    return serializerConverter;

}

From source file:com.hc.wx.server.common.bytecode.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 ArrayList<Object>(0);
    } else if (returnType.isAssignableFrom(HashSet.class)) {
        return new HashSet<Object>(0);
    } else if (returnType.isAssignableFrom(HashMap.class)) {
        return new HashMap<Object, Object>(0);
    } else if (String.class.equals(returnType)) {
        return "";
    } else if (!returnType.isInterface()) {
        try {//from   w  ww. j a va2s . 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.commonjava.rwx.binding.internal.xbr.XBRBindingContext.java

@SuppressWarnings("unchecked")
protected Binder newBinder(final Binder parent, final Class<?> type, final Field field) throws BindException {
    Converter bindVia = null;// ww w.java2s . com
    if (field != null) {
        bindVia = field.getAnnotation(Converter.class);
        if (bindVia == null) {
            bindVia = field.getType().getAnnotation(Converter.class);
        }
    }

    Logger logger = LoggerFactory.getLogger(getClass());
    logger.trace("Using ValueBinder: {} for field: {}", bindVia, field);

    Binder binder = null;
    if (bindVia != null && field.getAnnotation(Contains.class) == null) {
        return XBRBinderInstantiator.newValueBinder(bindVia, parent, type, this);
    } else if (Map.class.isAssignableFrom(type)) {
        binder = new MapBinder(parent, type, field, this);
    } else if (Collection.class.isAssignableFrom(type)) {
        binder = new CollectionBinder(parent, type, field, this);
    } else if (type.isArray() && !type.getComponentType().isPrimitive()) {
        binder = new ArrayBinder(parent, type.getComponentType(), field, this);
    } else if (bindVia != null) {
        return XBRBinderInstantiator.newValueBinder(bindVia, parent, type, this);
    } else if (mappings.containsKey(type)) {
        final Mapping<?> mapping = mappings.get(type);

        if (isMessage(type)) {
            return new MessageBinder(type, (ArrayMapping) mapping, this);
        } else if (hasAnnotation(type, ArrayPart.class)) {
            binder = new ArrayMappingBinder(parent, type, (ArrayMapping) mapping, this);
        } else if (hasAnnotation(type, StructPart.class)) {
            binder = new StructMappingBinder(parent, type, (StructMapping) mapping, this);
        } else {
            throw new BindException("Unknown Mapping: " + mapping);
        }

    }

    return binder;
}