Example usage for java.lang Class isPrimitive

List of usage examples for java.lang Class isPrimitive

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public native boolean isPrimitive();

Source Link

Document

Determines if the specified Class object represents a primitive type.

Usage

From source file:com.espertech.esper.util.MethodResolver.java

private static int compareParameterTypesNoContext(Class[] declarationParameters, Class[] invocationParameters,
        boolean[] optionalAllowEventBeanType, boolean[] optionalAllowEventBeanCollType,
        Type[] genericParameterTypes) {
    if (invocationParameters == null) {
        return declarationParameters.length == 0 ? 0 : -1;
    }//from w ww. j  a va 2 s  .c om

    if (declarationParameters.length != invocationParameters.length) {
        return -1;
    }

    int conversionCount = 0;
    int count = 0;
    for (Class parameter : declarationParameters) {
        if ((invocationParameters[count] == null) && !(parameter.isPrimitive())) {
            count++;
            continue;
        }
        if (optionalAllowEventBeanType != null && parameter == EventBean.class
                && optionalAllowEventBeanType[count]) {
            count++;
            continue;
        }
        if (optionalAllowEventBeanCollType != null && parameter == Collection.class
                && optionalAllowEventBeanCollType[count]
                && JavaClassHelper.getGenericType(genericParameterTypes[count], 0) == EventBean.class) {
            count++;
            continue;
        }
        if (!isIdentityConversion(parameter, invocationParameters[count])) {
            conversionCount++;
            if (!isWideningConversion(parameter, invocationParameters[count])) {
                conversionCount = -1;
                break;
            }
        }
        count++;
    }

    return conversionCount;
}

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

/**
* Parses object with follow rules://ww w. ja v  a2s.co 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;
}

From source file:com.expressui.core.util.ReflectionUtil.java

/**
 * Converts object value to given type. Converts primitives to their wrappers.
 * Converts strings to numbers.//from   ww  w . ja va 2  s.c om
 *
 * @param value value to convert
 * @param type  type to convert to
 * @param <T>   type
 * @return converted value
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws NoSuchMethodException
 */
public static <T> T convertValue(Object value, Class<T> type) throws InvocationTargetException,
        IllegalAccessException, InstantiationException, NoSuchMethodException {
    Class clazz;
    if (type.isPrimitive()) {
        clazz = ClassUtils.primitiveToWrapper(type);
    } else {
        clazz = type;
    }

    if (null == value || clazz.isAssignableFrom(value.getClass())) {
        return (T) value;
    }

    Constructor<T> constructor = clazz.getConstructor(new Class[] { String.class });

    return constructor.newInstance(value.toString());
}

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

/**
 * Parses object with follow rules:/*from   w w w.j a v a 2  s  .  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 java.lang.String},
 *  arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s,
 *  list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes},
 *  {@link com.vk.sdkweb.api.model.VKApiModel}s.
 *
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T> type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings("rawtypes")
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;
}

From source file:com.plusub.lib.annotate.JsonParserUtils.java

/**
 * ?/*  w  w  w.  j av a 2  s.  com*/
 * <p>Title: isWrapClass
 * <p>Description: 
 * @param clazz
 * @return
 */
private static boolean isBaseDataType(Class clazz) {
    return (clazz.isPrimitive() || clazz.equals(String.class) || clazz.equals(Integer.class)
            || clazz.equals(Boolean.class) || clazz.equals(Long.class) || clazz.equals(Double.class)
            || clazz.equals(Float.class) || clazz.equals(Short.class) || clazz.equals(Character.class)
            || clazz.equals(Date.class)) || clazz.equals(Byte.class) || clazz.equals(Void.class)
            || clazz.equals(BigDecimal.class) || clazz.equals(BigInteger.class);
}

From source file:com.google.gdt.eclipse.designer.ie.util.ReflectionUtils.java

/**
 * @param clazz/*w ww  .j  av a 2  s.c  om*/
 *            the class
 * @param runtime
 *            flag <code>true</code> if we need name for class loading, <code>false</code> if we need name
 *            for source generation.
 * 
 * @return the fully qualified name of given {@link Class}
 */
public static String getFullyQualifiedName(Class<?> clazz, boolean runtime) {
    Assert.isNotNull(clazz);
    if (runtime) {
        // primitive
        if (clazz.isPrimitive()) {
            if (clazz == void.class) {
                return "V";
            } else if (clazz == boolean.class) {
                return "Z";
            } else if (clazz == byte.class) {
                return "B";
            } else if (clazz == char.class) {
                return "C";
            } else if (clazz == short.class) {
                return "S";
            } else if (clazz == int.class) {
                return "I";
            } else if (clazz == long.class) {
                return "J";
            } else if (clazz == float.class) {
                return "F";
            } else if (clazz == double.class) {
                return "D";
            }
        }
        // array
        if (clazz.isArray()) {
            return "[" + getFullyQualifiedName(clazz.getComponentType(), runtime);
        }
        // object
        return "L" + clazz.getName() + ";";
    } else {
        // primitive
        if (clazz.isPrimitive()) {
            return clazz.getName();
        }
        // array
        if (clazz.isArray()) {
            return getFullyQualifiedName(clazz.getComponentType(), runtime) + "[]";
        }
        // object
        return clazz.getName().replace('/', '.').replace('$', '.');
    }
}

From source file:io.coala.json.JsonUtil.java

/**
 * @param om the {@link ObjectMapper} used to parse/deserialize/unmarshal
 * @param type the {@link Class} to register
 * @param imports the {@link Properties} instances for default values, etc.
 * @return/*from   w  w  w  .jav  a2  s .co m*/
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Class<T> checkRegistered(final ObjectMapper om, final Class<T> type,
        final Properties... imports) {
    synchronized (JSON_REGISTRATION_CACHE) {
        if (type.isPrimitive())
            return type;
        Set<Class<?>> cache = JSON_REGISTRATION_CACHE.computeIfAbsent(om, key -> new HashSet<>());
        if (type.getPackage() == Object.class.getPackage() || type.getPackage() == Collection.class.getPackage()
                || type.isPrimitive()
                // assume java.lang.* and java.util.* are already mapped
                || TreeNode.class.isAssignableFrom(type) || cache.contains(type))
            return type;

        // use Class.forName(String) ?
        // see http://stackoverflow.com/a/9130560

        //         LOG.trace( "Register JSON conversion of type: {}", type    );
        if (type.isAnnotationPresent(BeanProxy.class)) {
            //            if( !type.isInterface() )
            //               return Thrower.throwNew( IllegalArgumentException.class,
            //                     "@{} must target an interface, but annotates: {}",
            //                     BeanProxy.class.getSimpleName(), type );

            DynaBean.registerType(om, type, imports);
            checkRegisteredMembers(om, type, imports);
            // LOG.trace("Registered Dynabean de/serializer for: " + type);
        } else if (Wrapper.class.isAssignableFrom(type)) {
            Wrapper.Util.registerType(om, (Class<? extends Wrapper>) type);
            checkRegisteredMembers(om, type, imports);
            // LOG.trace("Registered Wrapper de/serializer for: " + type);
        }
        // else
        // LOG.trace("Assume default de/serializer for: " + type);

        cache.add(type);

        return type;
    }
}

From source file:com.mawujun.util.AnnotationUtils.java

/**
 * <p>Checks if the specified type is permitted as an annotation member.</p>
 *
 * <p>The Java language specification only permits certain types to be used
 * in annotations. These include {@link String}, {@link Class}, primitive
 * types, {@link Annotation}, {@link Enum}, and single-dimensional arrays of
 * these types.</p>//from w  w w .  ja v a  2s.c  o m
 *
 * @param type the type to check, {@code null}
 * @return {@code true} if the type is a valid type to use in an annotation
 */
public static boolean isValidAnnotationMemberType(Class<?> type) {
    if (type == null) {
        return false;
    }
    if (type.isArray()) {
        type = type.getComponentType();
    }
    return type.isPrimitive() || type.isEnum() || type.isAnnotation() || String.class.equals(type)
            || Class.class.equals(type);
}

From source file:org.jfree.chart.demo.SymbolicXYPlotDemo.java

/**
 * Transform an primitive array to an object array.
 * /*from   ww w. j  a  va2s  . c o  m*/
 * @param arr
 *           the array.
 * @return an array.
 */
private static Object toArray(final Object arr) {

    if (arr == null) {
        return arr;
    }

    final Class cls = arr.getClass();
    if (!cls.isArray()) {
        return arr;
    }

    Class compType = cls.getComponentType();
    int dim = 1;
    while (!compType.isPrimitive()) {
        if (!compType.isArray()) {
            return arr;
        } else {
            dim++;
            compType = compType.getComponentType();
        }
    }

    final int[] length = new int[dim];
    length[0] = Array.getLength(arr);
    Object[] newarr = null;

    try {
        if (compType.equals(Integer.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Integer"), length);
        } else if (compType.equals(Double.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Double"), length);
        } else if (compType.equals(Long.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Long"), length);
        } else if (compType.equals(Float.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Float"), length);
        } else if (compType.equals(Short.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Short"), length);
        } else if (compType.equals(Byte.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Byte"), length);
        } else if (compType.equals(Character.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Character"), length);
        } else if (compType.equals(Boolean.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Boolean"), length);
        }
    } catch (ClassNotFoundException ex) {
        System.out.println(ex);
    }

    for (int i = 0; i < length[0]; i++) {
        if (dim != 1) {
            newarr[i] = toArray(Array.get(arr, i));
        } else {
            newarr[i] = Array.get(arr, i);
        }
    }
    return newarr;
}

From source file:com.xutils.view.ViewInjectorImpl.java

@SuppressWarnings("ConstantConditions")
private static void injectObject(Object handler, Class<?> handlerType, ViewFinder finder) {

    if (handlerType == null || IGNORED.contains(handlerType)) {
        return;/*  w  ww .  j a  v  a 2  s. co m*/
    }

    // inject view
    Field[] fields = handlerType.getDeclaredFields();
    if (fields != null && fields.length > 0) {
        for (Field field : fields) {

            Class<?> fieldType = field.getType();
            if (
            /* ??? */ Modifier.isStatic(field.getModifiers()) ||
            /* ?final */ Modifier.isFinal(field.getModifiers()) ||
            /* ? */ fieldType.isPrimitive() ||
            /* ? */ fieldType.isArray()) {
                continue;
            }

            ViewInject viewInject = field.getAnnotation(ViewInject.class);
            if (viewInject != null) {
                try {
                    View view = finder.findViewById(viewInject.value(), viewInject.parentId());
                    if (view != null) {
                        field.setAccessible(true);
                        field.set(handler, view);
                    } else {
                        throw new RuntimeException("Invalid id(" + viewInject.value() + ") for @ViewInject!"
                                + handlerType.getSimpleName());
                    }
                } catch (Throwable ex) {
                    LogUtil.e(ex.getMessage(), ex);
                }
            }
        }
    }

    // inject event
    Method[] methods = handlerType.getDeclaredMethods();
    if (methods != null && methods.length > 0) {
        for (Method method : methods) {

            if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPrivate(method.getModifiers())) {
                continue;
            }

            //??event
            Event event = method.getAnnotation(Event.class);
            if (event != null) {
                try {
                    // id?
                    int[] values = event.value();
                    int[] parentIds = event.parentId();
                    int parentIdsLen = parentIds == null ? 0 : parentIds.length;
                    //id?ViewInfo???
                    for (int i = 0; i < values.length; i++) {
                        int value = values[i];
                        if (value > 0) {
                            ViewInfo info = new ViewInfo();
                            info.value = value;
                            info.parentId = parentIdsLen > i ? parentIds[i] : 0;
                            method.setAccessible(true);
                            EventListenerManager.addEventMethod(finder, info, event, handler, method);
                        }
                    }
                } catch (Throwable ex) {
                    LogUtil.e(ex.getMessage(), ex);
                }
            }
        }
    }

    injectObject(handler, handlerType.getSuperclass(), finder);
}