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.phoenixnap.oss.ramlapisync.javadoc.JavaDocExtractor.java

/**
 * Extracts the Java Doc for a specific class from its Source code as well as any superclasses or implemented
 * interfaces./*  w  ww .ja v a2 s  . co m*/
 * 
 * @param clazz The Class for which to get javadoc
 * @return A parsed documentation store with the class's Javadoc or empty if none is found.
 */
public JavaDocStore getJavaDoc(Class<?> clazz) {

    if (clazz.isArray()) {
        clazz = clazz.getComponentType();
    }
    // we need to start off from some base directory
    if (baseDir == null || clazz.isPrimitive()) {
        return new JavaDocStore();
    }

    String classPackage = clazz.getPackage() == null ? "" : clazz.getPackage().getName();
    // lets eliminate some stardard stuff
    if (classPackage.startsWith("java") || (classPackage.startsWith("org")
            && (classPackage.startsWith("org.hibernate") || classPackage.startsWith("org.raml")
                    || classPackage.startsWith("org.springframework")))) {
        return new JavaDocStore();
    }

    if (javaDocCache.containsKey(clazz)) {
        return javaDocCache.get(clazz);
    }
    logger.debug("Getting Javadoc for: " + clazz.getSimpleName());
    JavaDocStore javaDoc = new JavaDocStore();

    try {

        File file = FileSearcher.fileSearch(baseDir, clazz);

        if (file != null) {
            logger.debug("Found: " + file.getAbsolutePath());
            FileInputStream in = new FileInputStream(file);

            CompilationUnit cu;
            try {
                // parse the file
                cu = JavaParser.parse(in);
            } finally {
                in.close();
            }
            // visit and print the class docs names
            new ClassVisitor(javaDoc).visit(cu, null);
            // visit and print the methods names
            new MethodVisitor(javaDoc).visit(cu, null);
            // visit and print the field names
            new FieldVisitor(javaDoc).visit(cu, null);
        } else {
            logger.warn("*** WARNING: Missing Source for: " + clazz.getSimpleName() + ". JavaDoc Unavailable.");
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
    // After we complete this class, we need to check its parents and interfaces to extract as much documentation as
    // possible
    if (clazz.getInterfaces() != null && clazz.getInterfaces().length > 0) {
        for (Class<?> interfaceClass : clazz.getInterfaces()) {
            javaDoc.merge(getJavaDoc(interfaceClass));
        }
    }
    if (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class)) {
        javaDoc.merge(getJavaDoc(clazz.getSuperclass()));
    }

    javaDocCache.put(clazz, javaDoc);
    return javaDoc;
}

From source file:fi.foyt.foursquare.api.JSONFieldParser.java

/**
 * Parses single JSON object field into a value. Value might be of type String, Integer, Long, Double, Boolean or FoursquareEntity depending classes field type
 * /*from w w w . ja v  a2 s.  co  m*/
 * @param clazz class
 * @param jsonObject JSON Object
 * @param objectFieldName field to be parsed
 * @param skipNonExistingFields whether parser should ignore non-existing fields
 * @return field's value
 * @throws JSONException when JSON parsing error occures
 * @throws FoursquareApiException when something unexpected happens
 */
private static Object parseValue(Class<?> clazz, JSONObject jsonObject, String objectFieldName,
        boolean skipNonExistingFields) throws JSONException, FoursquareApiException {
    if (clazz.isArray()) {
        Object value = jsonObject.get(objectFieldName);

        JSONArray jsonArray;
        if (value instanceof JSONArray) {
            jsonArray = (JSONArray) value;
        } else {
            if ((value instanceof JSONObject) && (((JSONObject) value).has("items"))) {
                jsonArray = ((JSONObject) value).getJSONArray("items");
            } else {
                throw new FoursquareApiException("JSONObject[\"" + objectFieldName
                        + "\"] is neither a JSONArray nor a {count, items} object.");
            }
        }

        Class<?> arrayClass = clazz.getComponentType();
        Object[] arrayValue = (Object[]) Array.newInstance(arrayClass, jsonArray.length());

        for (int i = 0, l = jsonArray.length(); i < l; i++) {
            if (arrayClass.equals(String.class)) {
                arrayValue[i] = jsonArray.getString(i);
            } else if (arrayClass.equals(Integer.class)) {
                arrayValue[i] = jsonArray.getInt(i);
            } else if (arrayClass.equals(Long.class)) {
                arrayValue[i] = jsonArray.getLong(i);
            } else if (arrayClass.equals(Double.class)) {
                arrayValue[i] = jsonArray.getDouble(i);
            } else if (arrayClass.equals(Boolean.class)) {
                arrayValue[i] = jsonArray.getBoolean(i);
            } else if (isFoursquareEntity(arrayClass)) {
                arrayValue[i] = parseEntity(arrayClass, jsonArray.getJSONObject(i), skipNonExistingFields);
            } else {
                throw new FoursquareApiException("Unknown array type: " + arrayClass);
            }
        }

        return arrayValue;
    } else if (clazz.equals(String.class)) {
        return jsonObject.getString(objectFieldName);
    } else if (clazz.equals(Integer.class)) {
        return jsonObject.getInt(objectFieldName);
    } else if (clazz.equals(Long.class)) {
        return jsonObject.getLong(objectFieldName);
    } else if (clazz.equals(Double.class)) {
        return jsonObject.getDouble(objectFieldName);
    } else if (clazz.equals(Boolean.class)) {
        return jsonObject.getBoolean(objectFieldName);
    } else if (isFoursquareEntity(clazz)) {
        return parseEntity(clazz, jsonObject.getJSONObject(objectFieldName), skipNonExistingFields);
    } else {
        throw new FoursquareApiException("Unknown type: " + clazz);
    }
}

From source file:ClassReader.java

private static void addDescriptor(StringBuffer b, Class c) {
    if (c.isPrimitive()) {
        if (c == void.class) {
            b.append('V');
        } else if (c == int.class) {
            b.append('I');
        } else if (c == boolean.class) {
            b.append('Z');
        } else if (c == byte.class) {
            b.append('B');
        } else if (c == short.class) {
            b.append('S');
        } else if (c == long.class) {
            b.append('J');
        } else if (c == char.class) {
            b.append('C');
        } else if (c == float.class) {
            b.append('F');
        } else if (c == double.class) {
            b.append('D');
        }// w  ww. j a va2s.co  m
    } else if (c.isArray()) {
        b.append('[');
        addDescriptor(b, c.getComponentType());
    } else {
        b.append('L').append(c.getName().replace('.', '/')).append(';');
    }
}

From source file:com.nfwork.dbfound.json.converter.NumberArrayConverter.java

protected int getDimensions(Class arrayClass) {
    if (arrayClass == null || !arrayClass.isArray()) {
        return 0;
    }//w w w.j  a v a  2s. c o  m

    return 1 + getDimensions(arrayClass.getComponentType());
}

From source file:io.github.theangrydev.yatspeczohhakplugin.json.JsonCollectionsParameterCoercer.java

@Override
public Object coerceParameter(Type type, String stringToParse) {
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Class<?> rawType = (Class<?>) parameterizedType.getRawType();
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        return coerceParameterizedType(stringToParse, actualTypeArguments, rawType);
    } else if (type instanceof Class) {
        Class<?> targetType = ClassUtils.primitiveToWrapper((Class<?>) type);
        if (targetType.isArray()) {
            return coerceCollection(stringToParse, targetType.getComponentType(), ArrayBuilder::new);
        }// w  w w .ja v  a  2s  .  c om
        return defaultParameterCoercer.coerceParameter(targetType, stringToParse);
    } else {
        throw new IllegalArgumentException(format("Cannot interpret '%s' as a '%s'", stringToParse, type));
    }
}

From source file:org.brekka.phalanx.core.services.impl.AbstractCryptoService.java

protected byte[] toBytes(Object obj) {
    byte[] retVal;
    if (obj == null) {
        throw new NullPointerException("An object to encrypt must be specified");
    }// w  ww .ja va  2 s . c  o m
    Class<?> clazz = obj.getClass();
    if (clazz.isArray() && clazz.getComponentType() == Byte.TYPE) {
        retVal = (byte[]) obj;
    } else if (obj instanceof InternalPrivateKeyToken) {
        InternalPrivateKeyToken pkt = (InternalPrivateKeyToken) obj;
        retVal = encodePrivateKey(pkt);
    } else if (obj instanceof InternalSecretKeyToken) {
        InternalSecretKeyToken iskt = (InternalSecretKeyToken) obj;
        retVal = encodeSecretKey(iskt);
    } else {
        throw new IllegalArgumentException(
                String.format("Unsupport type conversion from '%s'", clazz.getName()));
    }
    return retVal;
}

From source file:com.adobe.acs.commons.util.impl.ValueMapTypeConverter.java

private Object handleArrayProperty(Class<?> clazz) {
    // handle case of primitive/wrapper arrays
    Class<?> componentType = clazz.getComponentType();
    if (componentType.isPrimitive()) {
        Class<?> wrapper = ClassUtils.primitiveToWrapper(componentType);
        if (wrapper != componentType) {
            Object wrapperArray = getValueFromMap(Array.newInstance(wrapper, 0).getClass());
            if (wrapperArray != null) {
                return unwrapArray(wrapperArray, componentType);
            }// w ww. j a v a 2s.  c o m
        }
    } else {
        Object wrapperArray = getValueFromMap(Array.newInstance(componentType, 0).getClass());
        if (wrapperArray != null) {
            return unwrapArray(wrapperArray, componentType);
        }
    }
    return null;
}

From source file:egovframework.rte.itl.webservice.service.impl.MessageConverterImpl.java

@SuppressWarnings("unchecked")
public Object convertToValueObject(Object source, Type type)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
    LOG.debug("convertToValueObject(source = " + source + ", type = " + type + ")");

    if (type instanceof PrimitiveType) {
        LOG.debug("Type is a Primitive Type");
        return source;
    } else if (type instanceof ListType) {
        LOG.debug("Type is a List Type");

        ListType listType = (ListType) type;
        Object[] components = ((Collection<?>) source).toArray();

        Class<?> arrayClass = classLoader.loadClass(listType);
        Object array = Array.newInstance(arrayClass.getComponentType(), components.length);

        for (int i = 0; i < components.length; i++) {
            Array.set(array, i, convertToValueObject(components[i], listType.getElementType()));
        }/*from  w w  w . ja  v a  2s . c o m*/
        return array;
    } else if (type instanceof RecordType) {
        LOG.debug("Type is a Record(Map) Type");

        RecordType recordType = (RecordType) type;
        Map<String, Object> map = (Map<String, Object>) source;

        Class<?> recordClass = classLoader.loadClass(recordType);
        Object record = recordClass.newInstance();

        for (Entry<String, Object> entry : map.entrySet()) {
            Object fieldValue = convertToValueObject(entry.getValue(), recordType.getFieldType(entry.getKey()));
            recordClass.getField(entry.getKey()).set(record, fieldValue);
        }
        return record;
    }
    LOG.error("Type is invalid");
    throw new InstantiationException();
}

From source file:org.jabsorb.serializer.impl.ArraySerializer.java

public boolean canSerialize(Class clazz, Class jsonClazz) {
    Class cc = clazz.getComponentType();
    return (super.canSerialize(clazz, jsonClazz)
            || ((jsonClazz == null || jsonClazz == JSONArray.class) && (clazz.isArray() && !cc.isPrimitive()))
            || (clazz == java.lang.Object.class && jsonClazz == JSONArray.class));
}

From source file:com.metaparadigm.jsonrpc.ArraySerializer.java

public ObjectMatch tryUnmarshall(SerializerState state, Class clazz, Object o) throws UnmarshallException {
    JSONArray jso = (JSONArray) o;//from   w  ww  . j  a  va2 s. c  o m
    Class cc = clazz.getComponentType();
    int i = 0;
    ObjectMatch m = new ObjectMatch(-1);
    try {
        for (; i < jso.length(); i++)
            m = ser.tryUnmarshall(state, cc, jso.get(i)).max(m);
    } catch (UnmarshallException e) {
        throw new UnmarshallException("element " + i + " " + e.getMessage());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return m;
}