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.dianping.resource.io.util.ClassUtils.java

/**
 * Return a descriptive name for the given object's type: usually simply
 * the class name, but component type class name + "[]" for arrays,
 * and an appended list of implemented interfaces for JDK proxies.
 * @param value the value to introspect// w  w w .  j  a  v  a 2 s. c om
 * @return the qualified name of the class
 */
public static String getDescriptiveType(Object value) {
    if (value == null) {
        return null;
    }
    Class<?> clazz = value.getClass();
    if (Proxy.isProxyClass(clazz)) {
        StringBuilder result = new StringBuilder(clazz.getName());
        result.append(" implementing ");
        Class<?>[] ifcs = clazz.getInterfaces();
        for (int i = 0; i < ifcs.length; i++) {
            result.append(ifcs[i].getName());
            if (i < ifcs.length - 1) {
                result.append(',');
            }
        }
        return result.toString();
    } else if (clazz.isArray()) {
        return getQualifiedNameForArray(clazz);
    } else {
        return clazz.getName();
    }
}

From source file:com.freetmp.common.util.ClassUtils.java

public static String getDescriptiveType(Object value) {
    if (value == null) {
        return null;
    }/* ww w  .  j  a v a 2  s .c om*/
    Class<?> clazz = value.getClass();
    if (Proxy.isProxyClass(clazz)) {
        StringBuilder result = new StringBuilder(clazz.getName());
        result.append(" implementing ");
        Class<?>[] ifcs = clazz.getInterfaces();
        for (int i = 0; i < ifcs.length; i++) {
            result.append(ifcs[i].getName());
            if (i < ifcs.length - 1) {
                result.append(',');
            }
        }
        return result.toString();
    } else if (clazz.isArray()) {
        return getQualifiedNameForArray(clazz);
    } else {
        return clazz.getName();
    }
}

From source file:coria2015.server.JsonRPCMethods.java

private int convert(Object p, Arguments description, int score, Object args[], int index) {
        Object o;/*from  w  w w. j  a  va  2s.  c  o m*/
        if (p instanceof JSONObject)
            // If p is a map, then use the json name of the argument
            o = ((JSONObject) p).get(description.getArgument(index).name());

        else if (p instanceof JSONArray)
            // if it is an array, then map it
            o = ((JSONArray) p).get(index);
        else {
            // otherwise, suppose it is a one value array
            if (index > 0)
                return Integer.MIN_VALUE;
            o = p;
        }

        final Class aType = description.getType(index);

        if (o == null) {
            if (description.getArgument(index).required())
                return Integer.MIN_VALUE;

            return score - 10;
        }

        if (aType.isArray()) {
            if (o instanceof JSONArray) {
                final JSONArray array = (JSONArray) o;
                final Object[] arrayObjects = args != null ? new Object[array.size()] : null;
                Arguments arguments = new Arguments() {
                    @Override
                    public RPCArgument getArgument(int i) {
                        return new RPCArrayArgument();
                    }

                    @Override
                    public Class<?> getType(int i) {
                        return aType.getComponentType();
                    }

                    @Override
                    public int size() {
                        return array.size();
                    }
                };
                for (int i = 0; i < array.size() && score > Integer.MIN_VALUE; i++) {
                    score = convert(array.get(i), arguments, score, arrayObjects, i);
                }
                return score;
            }
            return Integer.MIN_VALUE;
        }

        if (aType.isAssignableFrom(o.getClass())) {
            if (args != null)
                args[index] = o;
            return score;
        }

        if (o.getClass() == Long.class && aType == Integer.class) {
            if (args != null)
                args[index] = ((Long) o).intValue();
            return score - 1;
        }

        return Integer.MIN_VALUE;
    }

From source file:com.orange.mmp.api.ws.jsonrpc.SimpleJSONSerializer.java

/**
 * Replace getClassFromHint from super class to avoid using class hint
 * @param o a JSONObject or JSONArray object to get the Class type
 * @return the Class found, or null if the passed in Object is null
 *
 * @throws UnmarshallException if javaClass was not found
 *//* ww  w  . j  av a2  s .c o  m*/
@SuppressWarnings("unchecked")
private Class getClass(Object o) throws UnmarshallException {
    if (o == null) {
        return null;
    }

    if (o instanceof JSONArray) {
        JSONArray arr = (JSONArray) o;
        if (arr.length() == 0) {
            //             throw new UnmarshallException("no type for empty array");
            try {
                return Class.forName("[L" + Integer.class.getName() + ";");
            } catch (ClassNotFoundException e) {
                // XXX Warning: if this block doesn't fit, just throw the following exception
                // This block is used by SynchronizeAPI, when an empty blocks list is provided 
                throw new UnmarshallException("no type for empty array");
            }
        }

        Class compClazz;
        try {
            compClazz = getClass(arr.get(0));
            int arrayLgth = arr.length();
            for (int index = 0; index < arrayLgth; index++) {
                if (!getClass(arr.get(index)).isAssignableFrom(compClazz)) {
                    return java.util.List.class;
                }
            }
        } catch (JSONException e) {
            throw (NoSuchElementException) new NoSuchElementException(e.getMessage()).initCause(e);
        }

        try {
            if (compClazz.isArray()) {
                return Class.forName("[" + compClazz.getName());
            }
            return Class.forName("[L" + compClazz.getName() + ";");
        } catch (ClassNotFoundException e) {
            throw new UnmarshallException("problem getting array type");
        }
    }
    return o.getClass();
}

From source file:com.github.nmorel.gwtjackson.rebind.RebindConfiguration.java

/**
 * @param clazz class to find the type//  w  w w .j a  v  a 2s . c  o m
 *
 * @return the {@link JType} denoted by the class given in parameter
 */

private JType findType(Class<?> clazz) {
    if (clazz.isPrimitive()) {

        return JPrimitiveType.parse(clazz.getCanonicalName());

    } else if (clazz.isArray()) {

        try {
            return context.getTypeOracle().parse(clazz.getCanonicalName());
        } catch (TypeOracleException e) {
            logger.log(TreeLogger.WARN,
                    "Cannot find the array denoted by the class " + clazz.getCanonicalName());
            return null;
        }

    } else {
        return findClassType(clazz);
    }
}

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

/**
 * Infers the data type for the specified field once it has already been
 * processed for optional and collections.
 *
 * @author paouelle//  ww w.j a v a2s .com
 *
 * @param  field the non-<code>null</code> field to infer the CQL data type for
 * @param  clazz the non-<code>null</code> class for which to infer the CQL
 *         data type for the field
 * @param  types the non-<code>null</code> list where to add the inferred type and
 *         its arguments
 * @param  persisted the persisted annotation to consider for the field
 * @throws IllegalArgumentException if the data type cannot be inferred from
 *         the field
 */
private static void inferBasicDataTypeFrom(Field field, Class<?> clazz, List<CQLDataType> types,
        Persisted persisted) {
    if (persisted != null) {
        types.add(persisted.as());
    } else if (String.class == clazz) {
        types.add(DataType.TEXT);
    } else if (Integer.class == clazz) {
        types.add(DataType.INT);
    } else if (Long.class == clazz) {
        types.add(DataType.BIGINT);
    } else if (Boolean.class == clazz) {
        types.add(DataType.BOOLEAN);
    } else if (Date.class.isAssignableFrom(clazz)) {
        types.add(DataType.TIMESTAMP);
    } else if (Double.class == clazz) {
        types.add(DataType.DOUBLE);
    } else if (Float.class == clazz) {
        types.add(DataType.FLOAT);
    } else if (UUID.class.isAssignableFrom(clazz)) {
        types.add(DataType.UUID);
    } else if ((clazz.isArray() && (Byte.TYPE == clazz.getComponentType()))
            || ByteBuffer.class.isAssignableFrom(clazz)) {
        types.add(DataType.BLOB);
    } else if (BigDecimal.class.isAssignableFrom(clazz)) {
        types.add(DataType.DECIMAL);
    } else if (BigInteger.class.isAssignableFrom(clazz)) {
        types.add(DataType.VARINT);
    } else if (InetAddress.class.isAssignableFrom(clazz)) {
        types.add(DataType.INET);
    } else if (AtomicLong.class.isAssignableFrom(clazz)) {
        types.add(DataType.COUNTER);
    } else if (clazz.isEnum()) {
        types.add(DataType.ASCII);
    } else if (Class.class == clazz) {
        types.add(DataType.ASCII);
    } else if (Locale.class == clazz) {
        types.add(DataType.ASCII);
    } else if (ZoneId.class.isAssignableFrom(clazz)) {
        types.add(DataType.ASCII);
    } else if (Instant.class == clazz) {
        types.add(DataType.TIMESTAMP);
    } else {
        // check if it is a user-defined type
        try {
            final ClassInfoImpl<?> cinfo = (ClassInfoImpl<?>) StatementBuilder.getClassInfo(clazz);

            org.apache.commons.lang3.Validate.isTrue(cinfo instanceof UDTClassInfoImpl,
                    "unable to infer data type in field: %s", field);
            types.add((UDTClassInfoImpl<?>) cinfo);
        } catch (Exception e) {
            throw new IllegalArgumentException("unable to infer data type in field: " + field, e);
        }
    }
}

From source file:com.gigaspaces.persistency.metadata.DefaultSpaceDocumentMapper.java

private Object toExtractArray(BasicDBList value, Class<?> type) {
    if (type.isArray()) {
        return toArray(type, value);
    } else if (Collection.class.isAssignableFrom(type)) {
        return toCollection(type, value);
    } else if (Map.class.isAssignableFrom(type)) {
        return toMap(type, value);
    }/*from  www.  j  a v a2  s.c o  m*/

    throw new SpaceMongoException("invalid Array/Collection/Map type: " + type.getName());
}

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

private Object getValue(JSONArray array, Class<?> clazz) throws Exception {

    Object parsedArray = Array.newInstance(clazz, array.length());

    for (int c = 0; c < array.length(); ++c) {
        if ((clazz.equals(String.class) || clazz.isPrimitive()) && !clazz.equals(float.class)) {
            Array.set(parsedArray, c, array.get(c));
        } else if (clazz.equals(float.class)) {
            Array.set(parsedArray, c, (float) array.getDouble(c));
        } else if (clazz.isArray()) {
            // nested array
            Array.set(parsedArray, c, getValue(array.getJSONArray(c), float.class)); // TODO
        } else {//from   w w  w . j  ava  2s .  com
            Array.set(parsedArray, c, load(array.getJSONObject(c), clazz));
        }
    }

    return parsedArray;
}

From source file:com.jkoolcloud.tnt4j.streams.utils.Utils.java

/**
 * Checks if provided class represents an array class or is implementation of {@link java.util.Collection}.
 *
 * @param cls//from  w  ww .j av  a2 s  . c om
 *            class to check
 * @return {@code true} if cls is implementation of {@link java.util.Collection} or represents an array class,
 *         {@code false} - otherwise
 */
public static boolean isCollectionType(Class<?> cls) {
    return cls != null && (cls.isArray() || Collection.class.isAssignableFrom(cls));
}

From source file:com.vk.sdk.api.model.ParseUtils.java

/**
* Parses object with follow rules:/*from   www  .ja v  a2s. c o  m*/
*
* 1. All fields should had a public access.
* 2. The name of the filed should be fully equal to name of JSONObject key.
* 3. Supports parse of all Java primitives, all {@link String},
* arrays of primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s,
* list implementation line {@link com.vk.sdk.api.model.VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdk.api.model.VKPhotoSizes},
* {@link com.vk.sdk.api.model.VKApiModel}s.
*
* 4. Boolean fields defines by vk_int == 1 expression.
* @param object object to initialize
* @param source data to read values
* @return initialized according with given data object
* @throws JSONException if source object structure is invalid
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            // ?????????? ???????:
            // ?? ?? ????????, ?? ? ????????? ???????? getFields() ???????? ??? ???.
            // ?????? ? ??????? ???????????, ????????? ?? ? ????????, ?????? Android ? ???????? ????????? ??????????.
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}