Example usage for java.lang Class isArray

List of usage examples for java.lang Class isArray

Introduction

In this page you can find the example usage for java.lang Class isArray.

Prototype

@HotSpotIntrinsicCandidate
public native boolean isArray();

Source Link

Document

Determines if this Class object represents an array class.

Usage

From source file:ObjectAnalyzerTest.java

/**
 * Converts an object to a string representation that lists all fields.
 * /*from   ww  w .j av  a 2  s .c  om*/
 * @param obj
 *          an object
 * @return a string with the object's class name and all field names and
 *         values
 */
public String toString(Object obj) {
    if (obj == null)
        return "null";
    if (visited.contains(obj))
        return "...";
    visited.add(obj);
    Class cl = obj.getClass();
    if (cl == String.class)
        return (String) obj;
    if (cl.isArray()) {
        String r = cl.getComponentType() + "[]{";
        for (int i = 0; i < Array.getLength(obj); i++) {
            if (i > 0)
                r += ",";
            Object val = Array.get(obj, i);
            if (cl.getComponentType().isPrimitive())
                r += val;
            else
                r += toString(val);
        }
        return r + "}";
    }

    String r = cl.getName();
    // inspect the fields of this class and all superclasses
    do {
        r += "[";
        Field[] fields = cl.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        // get the names and values of all fields
        for (Field f : fields) {
            if (!Modifier.isStatic(f.getModifiers())) {
                if (!r.endsWith("["))
                    r += ",";
                r += f.getName() + "=";
                try {
                    Class t = f.getType();
                    Object val = f.get(obj);
                    if (t.isPrimitive())
                        r += val;
                    else
                        r += toString(val);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        r += "]";
        cl = cl.getSuperclass();
    } while (cl != null);

    return r;
}

From source file:grails.plugin.searchable.internal.compass.converter.DefaultCompassConverterLookupHelper.java

/**
 * Returns true if there is a registered Compass Converter for the given type
 * Also handles array types for supported array component types
 *
 * @param type a Class/* www .j a v a2 s .  c o m*/
 * @return true if a converter is available
 */
public boolean hasConverter(Class type) {
    Assert.notNull(converterLookup, "converterLookup cannot be null");
    Assert.notNull(type, "type cannot be null");
    if (type.isArray()) {
        type = type.getComponentType();
    }
    return converterLookup.lookupConverter(type) != null;
}

From source file:Main.java

public static Object getResource(Context context, Field field, int value) {
    Resources resources = context.getResources();
    Class type = field.getType();

    if (type.isAssignableFrom(Boolean.TYPE) || type.isAssignableFrom(Boolean.class))
        return resources.getBoolean(value);
    else if (type.isAssignableFrom(Integer.TYPE) || type.isAssignableFrom(Integer.class)) {
        return resources.getInteger(value);
    } else if (type.isAssignableFrom(ColorStateList.class))
        return resources.getColorStateList(value);
    else if (type.isAssignableFrom(XmlResourceParser.class))
        return resources.getXml(value);
    else if (type.isAssignableFrom(Float.TYPE) || type.isAssignableFrom(Float.class))
        return resources.getDimension(value);
    else if (type.isAssignableFrom(Drawable.class))
        return resources.getDrawable(value);
    else if (type.isAssignableFrom(Animation.class))
        return AnimationUtils.loadAnimation(context, value);
    else if (type.isAssignableFrom(Movie.class))
        return resources.getMovie(value);
    else if (type.isAssignableFrom(String.class))
        return resources.getString(value);
    else if (type.isArray()) {
        if (type.getName().equals("[I")) {
            return resources.getIntArray(value);
        } else if (type.isAssignableFrom(String[].class)) {
            return resources.getStringArray(value);
        }/*from   www.j a  v a2s  . c om*/
    }

    return null;
}

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.//from  ww w .  ja  v a  2s . c o 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:springfox.documentation.spring.web.readers.parameter.ExpandedParameterBuilder.java

private boolean isCollection(Class<?> fieldType) {
    return Collection.class.isAssignableFrom(fieldType) || fieldType.isArray();
}

From source file:org.codhaus.groovy.grails.validation.MaxSizeConstraint.java

@SuppressWarnings("rawtypes")
public boolean supports(Class type) {
    return type != null && (String.class.isAssignableFrom(type) || Collection.class.isAssignableFrom(type)
            || type.isArray());
}

From source file:com.bstek.dorado.data.type.manager.DataTypeManagerSupport.java

public DataType getDataType(Type type) throws Exception {
    DataTypeDefinition dataTypeDefinition = null;
    if (type instanceof Class<?>) {
        Class<?> cl = (Class<?>) type;
        if (!cl.isArray() && !Collection.class.isAssignableFrom(cl)) {
            dataTypeDefinition = getDefinedDataTypeDefinition(type);
        }/* w  w w .j a va2  s .  co m*/
    }
    if (dataTypeDefinition == null) {
        dataTypeDefinition = cachedTypesMap.get(type);
        if (dataTypeDefinition == null) {
            dataTypeDefinition = getDataTypeDefinition(type);
            if (dataTypeDefinition != null) {
                cachedTypesMap.put(type, dataTypeDefinition);
            }
        }
    }

    if (dataTypeDefinition == null) {
        throw new IllegalStateException("Can not found matching DataType for \"" + type + "\"!");
    }
    return getDataTypeByDefinition(dataTypeDefinition);
}

From source file:com.glaf.core.util.ReflectUtils.java

/**
 * get class desc. boolean[].class => "[Z" Object.class =>
 * "Ljava/lang/Object;"/*  ww  w  . j ava2 s.c  om*/
 * 
 * @param c
 *            class.
 * @return desc.
 * @throws NotFoundException
 */
public static String getDesc(Class<?> c) {
    StringBuilder ret = new StringBuilder();

    while (c.isArray()) {
        ret.append('[');
        c = c.getComponentType();
    }

    if (c.isPrimitive()) {
        String t = c.getName();
        if ("void".equals(t))
            ret.append(JVM_VOID);
        else if ("boolean".equals(t))
            ret.append(JVM_BOOLEAN);
        else if ("byte".equals(t))
            ret.append(JVM_BYTE);
        else if ("char".equals(t))
            ret.append(JVM_CHAR);
        else if ("double".equals(t))
            ret.append(JVM_DOUBLE);
        else if ("float".equals(t))
            ret.append(JVM_FLOAT);
        else if ("int".equals(t))
            ret.append(JVM_INT);
        else if ("long".equals(t))
            ret.append(JVM_LONG);
        else if ("short".equals(t))
            ret.append(JVM_SHORT);
    } else {
        ret.append('L');
        ret.append(c.getName().replace('.', '/'));
        ret.append(';');
    }
    return ret.toString();
}

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");
    }//from w w w.  j ava  2 s .  com
    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.glaf.core.util.GetterUtils.java

public static String[] getStringValues(Object value, String[] defaultValue) {

    if (value == null) {
        return defaultValue;
    }/*from  w  w  w. ja va2 s  .c  o m*/

    Class<?> clazz = value.getClass();

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

        if (String.class.isAssignableFrom(componentType)) {
            return getStringValues((String[]) value, defaultValue);
        }
    }

    return defaultValue;
}