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.geoserver.jdbcconfig.internal.DbMappings.java

private void addDirectPropertyTypes(final Class<? extends Info> clazz,
        final NamedParameterJdbcOperations template) {

    log("Creating property mappings for " + clazz.getName());

    final ClassProperties classProperties = new ClassProperties(clazz);

    List<String> properties = Lists.newArrayList(classProperties.properties());
    Collections.sort(properties);

    for (String propertyName : properties) {
        propertyName = fixCase(propertyName);
        Method getter = classProperties.getter(propertyName, null);
        if (getter == null) {
            continue;
        }/*from  ww w. java  2 s . c o  m*/

        Class<?> returnType = getter.getReturnType();

        if (returnType.isPrimitive() || returnType.isEnum() || INDEXABLE_TYPES.contains(returnType)) {

            final Class<?> componentType = returnType.isArray() ? returnType.getComponentType() : returnType;
            boolean isText = componentType.isEnum() || CharSequence.class.isAssignableFrom(componentType);

            isText &= !"id".equals(propertyName);// id is not on the full text search list of
                                                 // properties
            addPropertyType(template, clazz, propertyName, null, false, isText);
        } else {
            log("Ignoring property " + propertyName + ":" + returnType.getSimpleName());
        }
    }

    log("----------------------");
}

From source file:org.kmnet.com.fw.web.message.MessagesPanelTag.java

/**
 * Writes the messages which have been set in the model
 * <p>/*from   www.  j a  v  a 2s  .com*/
 * If messages stored in the model is in the form of a class that extends
 * {@code Iterable} or an Array, {@link #writeMessage(TagWriter, Object)} is
 * called multiple times, to write<br>
 * {@link #innerElement} and messages.<br>
 * 
 * If there is only a single message, this method calls
 * {@link #writeMessage(TagWriter, Object)} only once
 * </p>
 * 
 * @param tagWriter
 * @param messages
 * @throws JspException
 *             If {@link JspException} occurs in caller writeMessage
 */
protected void writeMessages(TagWriter tagWriter, Object messages) throws JspException {
    Class<?> clazz = messages.getClass();
    if (Iterable.class.isAssignableFrom(clazz)) {
        Iterable<?> col = (Iterable<?>) messages;
        for (Object message : col) {
            writeMessage(tagWriter, message);
        }
    } else if (clazz.isArray()) {
        Class<?> type = clazz.getComponentType();
        if (Object.class.isAssignableFrom(type)) {
            Object[] arr = (Object[]) messages;
            for (Object message : arr) {
                writeMessage(tagWriter, message);
            }
        } else {
            int len = Array.getLength(messages);
            for (int i = 0; i < len; i++) {
                Object message = Array.get(messages, i);
                writeMessage(tagWriter, message);
            }
        }
    } else {
        writeMessage(tagWriter, messages);
    }
}

From source file:com.espertech.esper.event.xml.XPathPropertyGetter.java

/**
 * Ctor.// w  ww. j a  v a2 s.  c o m
 * @param propertyName is the name of the event property for which this getter gets values
 * @param expressionText is the property expression itself
 * @param xPathExpression is a compile XPath expression
 * @param resultType is the resulting type
 * @param optionalCastToType if non-null then the return value of the xpath expression is cast to this value
 * @param fragmentFactory for creating fragments, or null in none to be created
 */
public XPathPropertyGetter(String propertyName, String expressionText, XPathExpression xPathExpression,
        QName resultType, Class optionalCastToType, FragmentFactory fragmentFactory) {
    this.expression = xPathExpression;
    this.expressionText = expressionText;
    this.property = propertyName;
    this.resultType = resultType;
    this.fragmentFactory = fragmentFactory;

    if ((optionalCastToType != null) && (optionalCastToType.isArray())) {
        isCastToArray = true;
        if (!resultType.equals(XPathConstants.NODESET)) {
            throw new IllegalArgumentException(
                    "Array cast-to types require XPathConstants.NODESET as the XPath result type");
        }
        optionalCastToType = optionalCastToType.getComponentType();
    } else {
        isCastToArray = false;
    }

    if (optionalCastToType != null) {
        simpleTypeParser = SimpleTypeParserFactory.getParser(optionalCastToType);
    } else {
        simpleTypeParser = null;
    }
    if (optionalCastToType == Node.class) {
        this.optionalCastToType = null;
    } else {
        this.optionalCastToType = optionalCastToType;
    }
}

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Checks all of the classes in the serialization scope that implement
 * TetradSerializable to make sure all of their fields are either themselves
 * (a) primitive, (b) TetradSerializable, or (c) assignable from types
 * designated as safely serializable by virtue of being included in the
 * safelySerializableTypes array (see), or are arrays whose lowest order
 * component types satisfy either (a), (b), or (c). Safely serializable
 * classes in the Java API currently include collections classes, plus
 * String and Class. Collections classes are included, since their types
 * will be syntactically checkable in JDK 1.5. String and Class are members
 * of a broader type of Class whose safely can by checked by making sure
 * there is no way to pass into them via constructor or method argument any
 * object that is not TetradSerializable or safely serializable. But it's
 * easy enough now to just make a list.//w w  w.j a v a2  s  .  c  o m
 *
 * @see #safelySerializableTypes
 */
public void checkNestingOfFields() {
    List classes = getAssignableClasses(new File(getSerializableScope()), TetradSerializable.class);

    boolean foundUnsafeField = false;

    for (Object aClass : classes) {
        Class clazz = (Class) aClass;

        if (TetradSerializableExcluded.class.isAssignableFrom(clazz)) {
            continue;
        }

        Field[] fields = clazz.getDeclaredFields();

        FIELDS: for (Field field : fields) {
            //                System.out.println(field);

            if (Modifier.isTransient(field.getModifiers())) {
                continue;
            }

            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }

            Class type = field.getType();

            while (type.isArray()) {
                type = type.getComponentType();
            }

            if (type.isPrimitive()) {
                continue;
            }

            if (type.isEnum()) {
                continue;
            }

            //                // Printing out Collections fields temporarily.
            //                if (Collection.class.isAssignableFrom(type)) {
            //                    System.out.println("COLLECTION FIELD: " + field);
            //                }
            //
            //                if (Map.class.isAssignableFrom(type)) {
            //                    System.out.println("MAP FIELD: " + field);
            //                }

            if (TetradSerializable.class.isAssignableFrom(type)
                    && !TetradSerializableExcluded.class.isAssignableFrom(clazz)) {
                continue;
            }

            for (Class safelySerializableClass : safelySerializableTypes) {
                if (safelySerializableClass.isAssignableFrom(type)) {
                    continue FIELDS;
                }
            }

            // A reference in an inner class to the outer class.
            if (field.getName().equals("this$0")) {
                continue;
            }

            System.out.println("UNSAFE FIELD:" + field);
            foundUnsafeField = true;
        }
    }

    if (foundUnsafeField) {
        throw new RuntimeException("Unsafe serializable fields found. Please " + "fix immediately.");
    }
}

From source file:org.ocelotds.core.services.ArgumentConvertor.java

private JavaType getJavaType(Type type) {
    Class clazz;
    logger.debug("Computing type of {} - {}", type.getClass(), type.toString());
    if (type instanceof ParameterizedType) {
        clazz = (Class) ((ParameterizedType) type).getRawType();
    } else {//  w  w  w  .  j ava2 s . c o m
        clazz = (Class) type;
    }
    JavaType javaType;
    Type actualType;
    if (Collection.class.isAssignableFrom(clazz)) {
        ParameterizedType pt = (ParameterizedType) type;
        actualType = pt.getActualTypeArguments()[0];
        JavaType t1 = getJavaType(actualType);
        javaType = CollectionType.construct(Collection.class, t1);
    } else if (clazz.isArray()) {
        Class t = clazz.getComponentType();
        JavaType t1 = getJavaType(t);
        javaType = ArrayType.construct(t1, null, null);
    } else if (Map.class.isAssignableFrom(clazz)) {
        ParameterizedType pt = (ParameterizedType) type;
        actualType = pt.getActualTypeArguments()[0];
        JavaType t1 = getJavaType(actualType);
        actualType = pt.getActualTypeArguments()[1];
        JavaType t2 = getJavaType(actualType);
        javaType = MapType.construct(Map.class, t1, t2);
    } else {
        javaType = SimpleType.construct(clazz);
    }
    return javaType;
}

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

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

    for (ExecutionResult result : results) {
        visitor.clearExceptions();
        visitor.setExceptions(result.exposeExceptionMapping());
        result.test.accept(visitor);
        imports.addAll(visitor.getImports());
        accessedClasses.addAll(result.test.getAccessedClasses());
        if (!hasException)
            hasException = !result.noThrownExceptions();
    }
    visitor.clearExceptions();

    if (doesUseMocks(results)) {
        String mockito = Mockito.class.getCanonicalName();
        builder.append("import static " + mockito + ".*;" + NEWLINE);
    }

    if (hasException) {
        builder.append("import static " + EvoAssertions.class.getCanonicalName() + ".*;" + NEWLINE);
    }

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

    if (TestSuiteWriterUtils.needToUseAgent()) {
        imports.add(EvoRunner.class);
        imports.add(EvoRunnerParameters.class);
        imports.add(RunWith.class);
    }

    Set<String> importNames = new HashSet<>();
    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("$"))
            importNames.add(imp.getName().replace("$", "."));
        else
            importNames.add(imp.getName());
    }

    for (Class<?> klass : EnvironmentDataList.getListOfClasses()) {
        //TODO: not paramount, but best if could check if actually used in the test suite
        if (accessedClasses.contains(klass))
            importNames.add(klass.getCanonicalName());
    }

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

    if (!Properties.TEST_SCAFFOLDING) {
        importNames.addAll(Scaffolding.getScaffoldingImports(wasSecurityException, results));
    }

    List<String> importsSorted = new ArrayList<String>(importNames);

    Collections.sort(importsSorted);
    for (String imp : importsSorted) {
        builder.append("import ");
        builder.append(imp);
        builder.append(";");
        builder.append(NEWLINE);
    }

    builder.append(NEWLINE);

    return builder.toString();
}

From source file:com.feilong.core.bean.ConvertUtil.java

/**
 * ? Primitive.//  w  ww .  j a  v a  2s . c  om
 *
 * @param o
 *            the o
 * @return true, if checks if is primitive array
 * 
 * @since 1.4.0
 */
private static boolean isPrimitiveArray(Object o) {
    // Allocate a new Array
    Class<? extends Object> klass = o.getClass();
    return !klass.isArray() ? false : klass.getComponentType().isPrimitive();//
}

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

/**
 * Return XML schema for the specified type, suitable for insertion into
 * the &lt;types&gt; element of a WSDL document, or underneath an
 * &lt;element&gt; or &lt;attribute&gt; declaration.
 *
 * @param javaType the Java Class we're writing out schema for
 * @param types the Java2WSDL Types object which holds the context
 *              for the WSDL being generated.
 * @return a type element containing a schema simpleType/complexType
 * @see org.apache.axis.wsdl.fromJava.Types
 *///ww w.  j  av  a2  s  . c  om
public Element writeSchema(Class javaType, Types types) throws Exception {
    boolean encoded = true;
    MessageContext mc = MessageContext.getCurrentContext();
    if (mc != null) {
        encoded = mc.isEncoded();
    } else {
        encoded = types.getServiceDesc().getUse() == Use.ENCODED;
    }

    if (!encoded) {
        Class cType = Object.class;
        if (javaType.isArray()) {
            cType = javaType.getComponentType();
        }

        String typeName = types.writeType(cType);
        return types.createLiteralArrayElement(typeName, null);
    }

    // If an array the component type should be processed first
    String componentTypeName = null;
    Class componentType = null;
    if (isArray(javaType)) {
        String dimString = "[]";
        componentType = getComponentType(javaType);
        while (isArray(componentType)) {
            dimString += "[]";
            componentType = getComponentType(componentType);
        }
        types.writeType(componentType, null);

        componentTypeName = types.getQNameString(types.getTypeQName(componentType)) + dimString;
    }

    // Use Types helper method to actually create the complexType
    return types.createArrayElement(componentTypeName);
}

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

/**
 * @param name/*w  w w  .j  a  v  a 2 s .co  m*/
 * @param returnType
 * @param parameters
 */
public ProxyMethod(Method method) {
    super();
    this.method = method;

    Class returnType = method.getReturnType();
    Class keyType = String.class;
    boolean prefetchResult = false;
    boolean cacheResult = false;
    isMap = Map.class.isAssignableFrom(returnType);
    com.zenesis.qx.remote.annotations.Method anno = method
            .getAnnotation(com.zenesis.qx.remote.annotations.Method.class);

    if (returnType.isArray() || Iterable.class.isAssignableFrom(returnType) || isMap) {
        // How to present on the client - only ArrayList by default is wrapped on the client
        Remote.Array array;
        if (returnType.isArray()) {
            returnType = returnType.getComponentType();
            array = Remote.Array.NATIVE;
        } else {
            returnType = Object.class;
            array = Remote.Array.WRAP;
        }

        // Component type
        if (anno != null) {
            if (anno.array() != Remote.Array.DEFAULT)
                array = anno.array();
            if (anno.arrayType() != Object.class)
                returnType = anno.arrayType();
            if (anno.keyType() != Object.class)
                keyType = anno.keyType();
        }
        this.array = array;
        this.arrayType = returnType;
    } else {
        array = null;
        this.arrayType = null;
    }

    if (anno != null) {
        if (method.getParameterTypes().length == 0) {
            prefetchResult = anno.prefetchResult();
            cacheResult = anno.cacheResult() || prefetchResult;
        }
    }

    this.keyType = keyType;
    this.prefetchResult = prefetchResult;
    this.staticMethod = (method.getModifiers() & Modifier.STATIC) != 0;
    if (staticMethod && cacheResult) {
        log.warn("Cannot cacheResult on static method " + method);
        cacheResult = false;
    }
    this.cacheResult = cacheResult;
}

From source file:com.sun.faces.renderkit.html_basic.MenuRenderer.java

protected Object handleArrayCase(FacesContext context, UISelectMany uiSelectMany, Class arrayClass,
        String[] newValues) throws ConverterException {
    Object result = null;/* w w w . j  a  v  a  2  s. c  om*/
    Class elementType = null;
    Converter converter = null;
    int i = 0, len = (null != newValues ? newValues.length : 0);

    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 = Util.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;
            }
            String valueStr = "";
            for (i = 0; i < newValues.length; i++) {
                valueStr = valueStr + " " + newValues[i];
            }
            Object[] params = { valueStr, "null Converter" };

            throw new ConverterException(Util.getExceptionMessage(Util.CONVERSION_ERROR_MESSAGE_ID, params));
        }
    }

    Util.doAssert(null != result);
    if (elementType.isPrimitive()) {
        for (i = 0; i < len; i++) {
            if (elementType.equals(Boolean.TYPE)) {
                Array.setBoolean(result, i,
                        ((Boolean) converter.getAsObject(context, uiSelectMany, newValues[i])).booleanValue());
            } else if (elementType.equals(Byte.TYPE)) {
                Array.setByte(result, i,
                        ((Byte) converter.getAsObject(context, uiSelectMany, newValues[i])).byteValue());
            } else if (elementType.equals(Double.TYPE)) {
                Array.setDouble(result, i,
                        ((Double) converter.getAsObject(context, uiSelectMany, newValues[i])).doubleValue());
            } else if (elementType.equals(Float.TYPE)) {
                Array.setFloat(result, i,
                        ((Float) converter.getAsObject(context, uiSelectMany, newValues[i])).floatValue());
            } else if (elementType.equals(Integer.TYPE)) {
                Array.setInt(result, i,
                        ((Integer) converter.getAsObject(context, uiSelectMany, newValues[i])).intValue());
            } else if (elementType.equals(Character.TYPE)) {
                Array.setChar(result, i,
                        ((Character) converter.getAsObject(context, uiSelectMany, newValues[i])).charValue());
            } else if (elementType.equals(Short.TYPE)) {
                Array.setShort(result, i,
                        ((Short) converter.getAsObject(context, uiSelectMany, newValues[i])).shortValue());
            } else if (elementType.equals(Long.TYPE)) {
                Array.setLong(result, i,
                        ((Long) converter.getAsObject(context, uiSelectMany, newValues[i])).longValue());
            }
        }
    } else {
        for (i = 0; i < len; i++) {
            if (log.isDebugEnabled()) {
                Object converted = converter.getAsObject(context, uiSelectMany, newValues[i]);
                log.debug("String value: " + newValues[i] + " converts to : " + converted.toString());
            }
            Array.set(result, i, converter.getAsObject(context, uiSelectMany, newValues[i]));
        }
    }
    return result;
}