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:com.gdevelop.gwt.syncrpc.SyncClientSerializationStreamReader.java

private Object instantiate(Class<?> customSerializer, Class<?> instanceClass)
        throws InstantiationException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, NoSuchMethodException, SerializationException {
    if (customSerializer != null) {
        for (Method method : customSerializer.getMethods()) {
            if ("instantiate".equals(method.getName())) {
                return method.invoke(null, this);
            }// w  w w.j  a v  a2  s .c  o  m
        }
        // Ok to not have one.
    }

    if (instanceClass.isArray()) {
        int length = readInt();
        // We don't pre-allocate the array; this prevents an allocation attack
        return new BoundedList<Object>(instanceClass.getComponentType(), length);
    } else if (instanceClass.isEnum()) {
        Enum<?>[] enumConstants = (Enum[]) instanceClass.getEnumConstants();
        int ordinal = readInt();
        assert (ordinal >= 0 && ordinal < enumConstants.length);
        return enumConstants[ordinal];
    } else {
        Constructor<?> constructor = instanceClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        return constructor.newInstance();
    }
}

From source file:com.github.helenusdriver.driver.impl.DataDecoder.java

/**
 * Gets an element decoder that can be used to convert a Cassandra
 * returned data type into another data type based on special supported
 * combinations./*from   w ww. j  av a2s .  c  o m*/
 *
 * @author paouelle
 *
 * @param  eclass the non-<code>null</code> element class to decode to
 * @param  reclass the non-<code>null</code> row's element class
 * @return a non-<code>null</code> element decoder for the provided combination
 * @throws IllegalArgumentException if the combination is not supported
 */
@SuppressWarnings("rawtypes")
static ElementConverter getConverter(final Class eclass, Class reclass) {
    if (Enum.class.isAssignableFrom(eclass) && (String.class == reclass)) {
        return new ElementConverter() {
            @SuppressWarnings("unchecked")
            @Override
            public Object convert(Object re) {
                return Enum.valueOf(eclass, (String) re);
            }
        };
    } else if (Locale.class.isAssignableFrom(eclass) && (String.class == reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return LocaleUtils.toLocale((String) re);
            }
        };
    } else if (ZoneId.class.isAssignableFrom(eclass) && (String.class == reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                try {
                    return ZoneId.of((String) re);
                } catch (DateTimeException e) {
                    throw new IllegalArgumentException(e);
                }
            }
        };
    } else if (eclass.isArray() && (Byte.TYPE == eclass.getComponentType())
            && ByteBuffer.class.isAssignableFrom(reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return Bytes.getArray((ByteBuffer) re);
            }
        };
    } else if ((Long.class == eclass) && Date.class.isAssignableFrom(reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return ((Date) re).getTime();
            }
        };
    } else if ((Instant.class == eclass) && Date.class.isAssignableFrom(reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return ((Date) re).toInstant();
            }
        };
    } else if (eclass == reclass) { // special case for maps
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return re;
            }
        };
    }
    throw new IllegalArgumentException(
            "unsupported element conversion from: " + reclass.getName() + " to: " + eclass.getName());
}

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

/**
 * Reads an array from JSON, where each value is of the listed in types; EG the first element
 * is class type[0], the second element is class type[1] etc
 * @param jp/*from w  ww.  ja v a 2s.  c o  m*/
 * @param types
 * @return
 * @throws IOException
 */
private Object[] readArray(JsonParser jp, Class[] types) throws IOException {
    if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
        return null;

    ArrayList result = new ArrayList();
    for (int paramIndex = 0; jp.nextToken() != JsonToken.END_ARRAY; paramIndex++) {
        Class type = null;
        if (types != null && paramIndex < types.length)
            type = types[paramIndex];

        if (type != null && type.isArray()) {
            if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
                result.add(null);
            else if (jp.getCurrentToken() == JsonToken.START_ARRAY) {
                Object obj = readArray(jp, type.getComponentType());
                result.add(obj);
            } else
                throw new IllegalStateException("Expected array but found " + jp.getCurrentToken());

        } else if (type != null && Proxied.class.isAssignableFrom(type)) {
            Integer id = jp.readValueAs(Integer.class);
            if (id != null) {
                Proxied obj = getProxied(id);
                result.add(obj);
            } else
                result.add(null);

        } else if (type != null && Enum.class.isAssignableFrom(type)) {
            Object obj = jp.readValueAs(Object.class);
            if (obj != null) {
                String str = Helpers.camelCaseToEnum(obj.toString());
                obj = Enum.valueOf(type, str);
                result.add(obj);
            }
        } else {
            Object obj = jp.readValueAs(type != null ? type : Object.class);
            result.add(obj);
        }
    }
    return result.toArray(new Object[result.size()]);
}

From source file:eu.sathra.io.IO.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Object getValue(JSONObject jObj, String param, Class<?> clazz)
        throws ArrayIndexOutOfBoundsException, IllegalArgumentException, Exception {
    try {/*from   w ww .j a  v a  2  s  .  c  o  m*/
        if (clazz.equals(String.class)) {
            return jObj.getString(param);
        } else if (clazz.equals(int.class)) {
            return jObj.getInt(param);
        } else if (clazz.equals(long.class)) {
            return jObj.getLong(param);
        } else if (clazz.equals(float.class)) {
            return (float) jObj.getDouble(param);
        } else if (clazz.equals(double.class)) {
            return jObj.getDouble(param);
        } else if (clazz.equals(boolean.class)) {
            return jObj.getBoolean(param);
        } else if (mAdapters.containsKey(clazz)) {
            return mAdapters.get(clazz).load(param, jObj);
        } else if (clazz.isEnum()) {
            return Enum.valueOf((Class<? extends Enum>) clazz, jObj.getString(param));
        } else if (clazz.isArray()) {
            return getValue(jObj.getJSONArray(param), clazz.getComponentType());
        } else {
            return load(jObj.getJSONObject(param), clazz);
        }
    } catch (JSONException e) {
        return null;
    } finally {
        jObj.remove(param);
    }

}

From source file:org.brushingbits.jnap.common.bean.visitor.BeanPropertyVisitor.java

/**
 * /*ww w . j  a va  2s .  c o m*/
 * @param source
 */
public void visit(Object source) {
    logger.warn("Source object is null, there is nothing to visit!");
    if (source != null) {
        debug("Visiting object...");
        final String currentPath = getCurrentPath();
        debug("...current path is: " + currentPath);
        final Class<?> type = this.propertyTypeResolver.resolve(source, this.propertyFilter);
        debug("...current type is: " + type.getName());

        final boolean excluded = type == null || shouldExcludeProperty(currentPath) || shouldExcludeType(type)
                || shouldExcludeAssignableType(type);
        debug("");
        final int currentLevel = context.getCurrentLevel();
        final boolean included = shouldIncludeProperty(currentPath) || currentLevel == -1;
        debug("");
        final boolean validDepth = propertyFilter.getDepth() == -1 || currentLevel <= propertyFilter.getDepth();
        debug("the current depth is " + currentLevel + ", max depth is " + propertyFilter.getDepth());
        if (included || (!excluded && validDepth)) {
            if (isStandardType(type)) {
                handleStandardProperty(source, type);
            } else if (type.isArray()) {
                handleArray((Object[]) source, type);
            } else if (Collection.class.isAssignableFrom(type)) {
                handleCollection((Collection<?>) source, type);
            } else if (Map.class.isAssignableFrom(type)) {
                handleMap((Map<?, ?>) source, type);
            } else {
                // so, we assume it's a nested bean (let's go 'down' another level)
                if (!context.wasAlreadyVisited(source) || !this.preventCircularVisiting) {
                    handleBean(source, type);
                }
            }
        }
    }
}

From source file:javadz.beanutils.ConvertUtilsBean.java

/**
 * Look up and return any registered {@link Converter} for the specified
 * source and destination class; if there is no registered Converter,
 * return <code>null</code>.
 *
 * @param sourceType Class of the value being converted
 * @param targetType Class of the value to be converted to
 * @return The registered {@link Converter} or <code>null</code> if not found
 *//*from  w  w  w  .  j a  v a  2s . c om*/
public Converter lookup(Class sourceType, Class targetType) {

    if (targetType == null) {
        throw new IllegalArgumentException("Target type is missing");
    }
    if (sourceType == null) {
        return lookup(targetType);
    }

    Converter converter = null;
    // Convert --> String 
    if (targetType == String.class) {
        converter = lookup(sourceType);
        if (converter == null && (sourceType.isArray() || Collection.class.isAssignableFrom(sourceType))) {
            converter = lookup(String[].class);
        }
        if (converter == null) {
            converter = lookup(String.class);
        }
        return converter;
    }

    // Convert --> String array 
    if (targetType == String[].class) {
        if (sourceType.isArray() || Collection.class.isAssignableFrom(sourceType)) {
            converter = lookup(sourceType);
        }
        if (converter == null) {
            converter = lookup(String[].class);
        }
        return converter;
    }

    return lookup(targetType);

}

From source file:com.seleniumtests.reporter.SeleniumTestsReporter.java

protected String getType(Class<?> cls) {

    while (cls.isArray()) {
        cls = cls.getComponentType();/*  w  w w .  jav a2 s  .  c o  m*/
    }

    return cls.getName();
}

From source file:com.openmeap.json.JSONObjectBuilder.java

public JSONObject toJSON(Object obj) throws JSONException {

    if (obj == null) {
        return null;
    }//from   w ww. j a  v a  2s.co m
    if (!HasJSONProperties.class.isAssignableFrom(obj.getClass())) {
        throw new RuntimeException(
                "The rootObject being converted to JSON must implement the HasJSONProperties interface.");
    }
    JSONProperty[] properties = ((HasJSONProperties) obj).getJSONProperties();
    JSONObject jsonObj = new JSONObject();

    // iterate over each JSONProperty annotated method
    for (int jsonPropertyIdx = 0; jsonPropertyIdx < properties.length; jsonPropertyIdx++) {

        JSONProperty property = properties[jsonPropertyIdx];

        // determine the method return type
        Class returnType = property.getReturnType();

        Object value = property.getGetterSetter().getValue(obj);
        if (value == null) {
            continue;
        }

        if (returnType == null) {
            throw new JSONException(obj.getClass().getName() + "." + property.getPropertyName()
                    + " is annotated with JSONProperty, but has no return type." + "  I can't work with this.");
        }

        // strip "get" off the front
        String propertyName = property.getPropertyName();

        try {
            if (Enum.class.isAssignableFrom(returnType)) {
                Enum ret = (Enum) value;
                jsonObj.put(propertyName, ret.value());
            } else if (isSimpleType(returnType)) {
                jsonObj.put(propertyName,
                        handleSimpleType(returnType, property.getGetterSetter().getValue(obj)));
            } else {
                if (returnType.isArray()) {
                    Object[] returnValues = (Object[]) value;
                    JSONArray jsonArray = new JSONArray();
                    for (int returnValueIdx = 0; returnValueIdx < returnValues.length; returnValueIdx++) {
                        Object thisValue = returnValues[returnValueIdx];
                        jsonArray.put(toJSON(thisValue));
                    }
                    jsonObj.put(propertyName, jsonArray);
                } else if (Hashtable.class.isAssignableFrom(returnType)) {
                    Hashtable map = (Hashtable) value;
                    JSONObject jsonMap = new JSONObject();
                    Enumeration enumer = map.keys();
                    while (enumer.hasMoreElements()) {
                        Object key = (String) enumer.nextElement();
                        Object thisValue = (Object) map.get(key);
                        if (isSimpleType(thisValue.getClass())) {
                            jsonMap.put(key.toString(), handleSimpleType(returnType, thisValue));
                        } else {
                            jsonMap.put(key.toString(), toJSON(thisValue));
                        }
                    }
                    jsonObj.put(propertyName, jsonMap);
                } else if (Vector.class.isAssignableFrom(returnType)) {

                    Vector returnValues = (Vector) property.getGetterSetter().getValue(obj);
                    JSONArray jsonArray = new JSONArray();
                    int size = returnValues.size();
                    for (int returnValueIdx = 0; returnValueIdx < size; returnValueIdx++) {
                        Object thisValue = returnValues.elementAt(returnValueIdx);
                        if (isSimpleType(property.getContainedType())) {
                            jsonArray.put(thisValue);
                        } else {
                            jsonArray.put(toJSON(thisValue));
                        }
                    }
                    jsonObj.put(propertyName, jsonArray);
                } else {
                    jsonObj.put(propertyName, toJSON(value));
                }
            }
        } catch (Exception ite) {
            throw new JSONException(ite);
        }

    }
    return jsonObj;
}

From source file:com.amalto.core.metadata.ClassRepository.java

private TypeMetadata loadClass(Class clazz) {
    String typeName = getTypeName(clazz);
    if (getType(typeName) != null) { // If already defined return it.
        return getType(typeName);
    } else if (getNonInstantiableType(StringUtils.EMPTY, typeName) != null) {
        return getNonInstantiableType(StringUtils.EMPTY, typeName);
    }/*from   w  w w.j ava  2  s.c o  m*/
    entityToJavaClass.put(typeName, clazz);
    if (Map.class.isAssignableFrom(clazz)) {
        return MAP_TYPE;
    }
    if (ArrayListHolder.class.equals(clazz)) {
        typeName = typeName + listCounter++;
    }
    boolean isEntity = typeStack.isEmpty();
    ComplexTypeMetadata classType = new ComplexTypeMetadataImpl(StringUtils.EMPTY, typeName, isEntity);
    addTypeMetadata(classType);
    typeStack.push(classType);
    String keyFieldName = ""; //$NON-NLS-1$
    if (isEntity && ObjectPOJO.class.isAssignableFrom(clazz)) {
        SimpleTypeFieldMetadata keyField = new SimpleTypeFieldMetadata(typeStack.peek(), true, false, true,
                "unique-id", //$NON-NLS-1$
                STRING, Collections.<String>emptyList(), Collections.<String>emptyList(),
                Collections.<String>emptyList(), StringUtils.EMPTY);
        keyField.setData(LINK, "PK/unique-id"); //$NON-NLS-1$
        classType.addField(keyField);
    } else if (isEntity) {
        keyFieldName = "unique-id"; //$NON-NLS-1$
    }
    // Class is abstract / interface: load sub classes
    if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
        Iterable<Class> subClasses = getSubclasses(clazz);
        ComplexTypeMetadata superType = typeStack.peek();
        if (superType.isInstantiable()) {
            typeStack.clear();
        }
        for (Class subClass : subClasses) {
            TypeMetadata typeMetadata = loadClass(subClass);
            typeMetadata.setInstantiable(superType.isInstantiable());
            typeMetadata.addSuperType(superType);
        }
        if (superType.isInstantiable()) {
            typeStack.push(superType);
        }
    }
    // Analyze methods
    Method[] classMethods = getMethods(clazz);
    for (Method declaredMethod : classMethods) {
        if (!Modifier.isStatic(declaredMethod.getModifiers())) {
            if (isBeanMethod(declaredMethod) && isClassMethod(clazz, declaredMethod)) {
                String fieldName = getName(declaredMethod);
                if (typeStack.peek().hasField(fieldName)) {
                    continue; // TODO Avoid override of fields (like PK)
                }
                Class<?> returnType = declaredMethod.getReturnType();
                FieldMetadata newField;
                boolean isMany = false;
                boolean isKey = keyFieldName.equals(fieldName);
                if (Iterable.class.isAssignableFrom(returnType)) {
                    returnType = listItemType != null ? listItemType
                            : getListItemClass(declaredMethod, returnType);
                    listItemType = null;
                    isMany = true;
                } else if (ArrayListHolder.class.isAssignableFrom(returnType)) {
                    listItemType = getListItemClass(declaredMethod, returnType);
                    isMany = false;
                } else if (Map.class.isAssignableFrom(returnType)) {
                    isMany = true;
                } else if (returnType.isArray()) {
                    isMany = true;
                    returnType = ((Class) returnType.getComponentType());
                } else if (returnType.getName().startsWith("org.w3c.")) { //$NON-NLS-1$
                    // TODO Serialized XML to string column
                    continue;
                } else if (Class.class.equals(returnType)) {
                    continue;
                } else if (returnType.getPackage() != null
                        && returnType.getPackage().getName().startsWith("java.io")) { //$NON-NLS-1$
                    continue;
                }
                if (returnType.isPrimitive() || returnType.getName().startsWith(JAVA_LANG_PREFIX)) {
                    String fieldTypeName = returnType.getName().toLowerCase();
                    if (fieldTypeName.startsWith(JAVA_LANG_PREFIX)) {
                        fieldTypeName = StringUtils.substringAfter(fieldTypeName, JAVA_LANG_PREFIX);
                    }
                    TypeMetadata fieldType;
                    if (Types.BYTE.equals(fieldTypeName) && isMany) {
                        fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI,
                                Types.BASE64_BINARY);
                    } else {
                        fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, fieldTypeName);
                    }
                    newField = new SimpleTypeFieldMetadata(typeStack.peek(), isKey, isMany, isKey, fieldName,
                            fieldType, Collections.<String>emptyList(), Collections.<String>emptyList(),
                            Collections.<String>emptyList(), StringUtils.EMPTY);
                    LongString annotation = declaredMethod.getAnnotation(LongString.class);
                    if (Types.STRING.equals(fieldTypeName) && annotation != null) {
                        fieldType.setData(MetadataRepository.DATA_MAX_LENGTH,
                                String.valueOf(Integer.MAX_VALUE));
                        if (annotation.preferLongVarchar()) {
                            fieldType.setData(LongString.PREFER_LONGVARCHAR, Boolean.TRUE);
                        }
                    }
                } else {
                    ComplexTypeMetadata fieldType;
                    if (Map.class.isAssignableFrom(returnType)) {
                        fieldType = MAP_TYPE;
                    } else {
                        fieldType = (ComplexTypeMetadata) loadClass(returnType);
                    }
                    if (!isEntity || !fieldType.isInstantiable()) {
                        newField = new ContainedTypeFieldMetadata(typeStack.peek(), isMany, false, fieldName,
                                new SoftTypeRef(this, StringUtils.EMPTY, fieldType.getName(), false),
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                Collections.<String>emptyList(), StringUtils.EMPTY);
                    } else {
                        newField = new ReferenceFieldMetadata(typeStack.peek(), false, isMany, false, fieldName,
                                fieldType, fieldType.getField("unique-id"), //$NON-NLS-1$
                                Collections.<FieldMetadata>emptyList(), StringUtils.EMPTY, true, false, STRING,
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                Collections.<String>emptyList(), StringUtils.EMPTY, StringUtils.EMPTY);
                    }
                }
                typeStack.peek().addField(newField);
            }
        }
    }

    typeStack.peek().addField(new SimpleTypeFieldMetadata(typeStack.peek(), false, false, false, "digest", //$NON-NLS-1$
            new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, Types.STRING),
            Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(),
            StringUtils.EMPTY));

    return typeStack.pop();
}