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:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Returns true if the specified clazz parameter is either the same as, or is a superclass or superinterface
 * of, the specified type parameter. Converts primitive types to compatible class automatically.
 *
 * @param clazz//ww w.  jav a 2s.  c o m
 * @param type
 * @return True if the class is a taglib
 * @see java.lang.Class#isAssignableFrom(Class)
 */
public static boolean isAssignableOrConvertibleFrom(Class clazz, Class type) {
    if (type == null || clazz == null) {
        return false;
    } else if (type.isPrimitive()) {
        // convert primitive type to compatible class
        Class primitiveClass = (Class) GriffonClassUtils.PRIMITIVE_TYPE_COMPATIBLE_CLASSES.get(type);
        if (primitiveClass == null) {
            // no compatible class found for primitive type
            return false;
        } else {
            return clazz.isAssignableFrom(primitiveClass);
        }
    } else {
        return clazz.isAssignableFrom(type);
    }
}

From source file:gov.nih.nci.system.web.util.RESTUtil.java

/**
 * Gets all the methods for a given class
 *
 * @param resultClass// w w w  . j a v a2  s .  c  o m
 *            - Specifies the class name
 * @return - Returns all the methods
 */
@SuppressWarnings({ "rawtypes" })
public static Method[] getAllMethods(Class resultClass) {
    List<Method> methodList = new ArrayList<Method>();
    try {
        while (resultClass != null && !resultClass.isInterface() && !resultClass.isPrimitive()) {
            Method[] method = resultClass.getDeclaredMethods();
            for (int i = 0; i < method.length; i++) {
                method[i].setAccessible(true);
                methodList.add(method[i]);
            }
            if (!resultClass.getSuperclass().getName().equalsIgnoreCase("java.lang.Object")) {
                resultClass = resultClass.getSuperclass();
            } else {
                break;
            }
        }
    } catch (Exception ex) {
        log.error("ERROR: " + ex.getMessage());
    }
    Method[] methods = new Method[methodList.size()];
    for (int i = 0; i < methodList.size(); i++) {
        methods[i] = methodList.get(i);
    }
    return methods;
}

From source file:com.bstek.dorado.data.entity.EntityUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T toEntity(Object object, DataType dataType) throws Exception {
    if (isSimpleValue(object)) {
        return (T) object;
    }//from  w w  w.  ja v a  2 s  . c o  m

    // Expression
    if (object instanceof Expression) {
        object = ((Expression) object).evaluate();
    }

    Class<?> cl = object.getClass();
    if (object instanceof Collection) {
        Collection<?> entities = (Collection<?>) object;
        if (entities instanceof EntityCollection<?>) {
            DataType currentDataType = getDataType(entities);
            if (currentDataType != dataType && dataType != null) {
                ((EntityCollection<?>) entities).setDataType((AggregationDataType) dataType);
            }
            return (T) object;
        }
    } else {
        EntityEnhancer entityEnhancer = getEntityEnhancer(object);
        if (entityEnhancer != null) {
            DataType currentDataType = entityEnhancer.getDataType();
            if (currentDataType != dataType && dataType != null) {
                entityEnhancer.setDataType((EntityDataType) dataType);
            }
            return (T) object;
        }
    }

    boolean useProxy = true;
    if (dataType == null) {
        dataType = getDataType(cl);
    }

    if (dataType != null) {
        Class<?> matchType = dataType.getMatchType();
        if (matchType != null) {
            boolean matching = false;
            if (matchType.isPrimitive()) {
                matching = ClassUtils.primitiveToWrapper(matchType).equals(cl);
            } else {
                matching = matchType.isAssignableFrom(cl);
            }
            if (!matching) {
                if (dataType instanceof EntityDataType) {
                    DataType realDataType = getDataType(cl);
                    if (realDataType instanceof EntityDataType) {
                        matching = true;
                        useProxy = false;
                    }
                } else if (dataType instanceof AggregationDataType) {
                    DataType realDataType = getDataType(cl);
                    if (realDataType instanceof AggregationDataType) {
                        matching = true;
                    }
                }

                if (!matching) {
                    throw new IllegalArgumentException(
                            "Result type mismatch. expect [" + matchType + "] but [" + cl + "].");
                }
            }
        }
    }

    if (object instanceof Collection) {
        // Collection???
        AggregationDataType AggregationDataType = (AggregationDataType) dataType;
        if (object instanceof List) {
            object = new EntityList((List) object, AggregationDataType);
        } else if (object instanceof Set) {
            object = new EntitySet((Set) object, AggregationDataType);
        } else {
            throw new IllegalArgumentException("Unsupported result type [" + cl.getName() + "].");
        }
    } else if (object.getClass().isArray()) {
        Class type = object.getClass();
        if (isSimpleType(type.getComponentType())) {
            return (T) object;
        } else {
            // ??java.util.List
            logger.warn("Dorado converted a " + object.getClass() + " to " + List.class + " automatically.");

            List list = CollectionUtils.arrayToList(object);
            object = new EntityList(list, (AggregationDataType) dataType);
        }
    } else {
        // TODO Entity????
        // Entity???
        EntityDataType entityDataType = (EntityDataType) dataType;
        if (!(entityDataType instanceof CustomEntityDataType)) {
            if (useProxy) {
                // ????
                if (object instanceof EnhanceableEntity) {
                    EnhanceableEntity enhanceableEntity = (EnhanceableEntity) object;
                    if (enhanceableEntity.getEntityEnhancer() == null) {
                        EntityEnhancer entityEnhancer;
                        if (object instanceof Map) {
                            entityEnhancer = new EnhanceableMapEntityEnhancer(entityDataType);
                        } else {
                            entityEnhancer = new EnhanceableBeanEntityEnhancer(entityDataType,
                                    object.getClass());
                        }
                        enhanceableEntity.setEntityEnhancer(entityEnhancer);
                    }
                    return (T) object;
                } else {
                    MethodInterceptor[] mis = getMethodInterceptorFactory().createInterceptors(entityDataType,
                            object.getClass(), object);
                    object = ProxyBeanUtils.proxyBean(object, mis);
                }
            } else {
                // ????
                Class<?> creationType = entityDataType.getCreationType();
                if (creationType == null) {
                    creationType = entityDataType.getMatchType();
                }

                Map map;
                if (object instanceof Map) {
                    map = (Map) object;
                } else {
                    map = BeanMap.create(object);
                }

                if (creationType == null) {
                    Record record = new Record(map);
                    record.setEntityEnhancer(new EnhanceableMapEntityEnhancer(entityDataType));
                    object = record;
                } else {
                    MethodInterceptor[] mis = getMethodInterceptorFactory().createInterceptors(entityDataType,
                            creationType, null);
                    object = ProxyBeanUtils.createBean(creationType, mis);
                    setValues(object, map);
                }
            }
        } else {
            object = ((CustomEntityDataType) entityDataType).toMap(object);
        }
    }
    return (T) object;
}

From source file:nl.strohalm.cyclos.utils.conversion.CoercionHelper.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object convert(Class toType, Object value) {
    if ("".equals(value)) {
        value = null;//w ww  .  j a  va2s  .  co m
    }
    // If we do not want a collection, but the value is one, use the first value
    if (value != null && !(Collection.class.isAssignableFrom(toType) || toType.isArray())
            && (value.getClass().isArray() || value instanceof Collection)) {
        final Iterator it = IteratorUtils.getIterator(value);
        if (!it.hasNext()) {
            value = null;
        } else {
            value = it.next();
        }
    }

    // Check for null values
    if (value == null) {
        if (toType.isPrimitive()) {
            // On primitives, use the default value
            if (toType == Boolean.TYPE) {
                value = Boolean.FALSE;
            } else if (toType == Character.TYPE) {
                value = '\0';
            } else {
                value = 0;
            }
        } else {
            // For objects, return null
            return null;
        }
    }

    // Check if the value is already of the expected type
    if (toType.isInstance(value)) {
        return value;
    }

    // If the class is primitive, use the wrapper, so we have an easier work of testing instances
    if (toType.isPrimitive()) {
        toType = ClassUtils.primitiveToWrapper(toType);
    }

    // Convert to well-known types
    if (String.class.isAssignableFrom(toType)) {
        if (value instanceof Entity) {
            final Long entityId = ((Entity) value).getId();
            return entityId == null ? null : entityId.toString();
        }
        return value.toString();
    } else if (Number.class.isAssignableFrom(toType)) {
        if (!(value instanceof Number)) {
            if (value instanceof String) {
                value = new BigDecimal((String) value);
            } else if (value instanceof Date) {
                value = ((Date) value).getTime();
            } else if (value instanceof Calendar) {
                value = ((Calendar) value).getTimeInMillis();
            } else if (value instanceof Entity) {
                value = ((Entity) value).getId();
                if (value == null) {
                    return null;
                }
            } else {
                throw new ConversionException("Invalid number: " + value);
            }
        }
        final Number number = (Number) value;
        if (Byte.class.isAssignableFrom(toType)) {
            return number.byteValue();
        } else if (Short.class.isAssignableFrom(toType)) {
            return number.shortValue();
        } else if (Integer.class.isAssignableFrom(toType)) {
            return number.intValue();
        } else if (Long.class.isAssignableFrom(toType)) {
            return number.longValue();
        } else if (Float.class.isAssignableFrom(toType)) {
            return number.floatValue();
        } else if (Double.class.isAssignableFrom(toType)) {
            return number.doubleValue();
        } else if (BigInteger.class.isAssignableFrom(toType)) {
            return new BigInteger(number.toString());
        } else if (BigDecimal.class.isAssignableFrom(toType)) {
            return new BigDecimal(number.toString());
        }
    } else if (Boolean.class.isAssignableFrom(toType)) {
        if (value instanceof Number) {
            return ((Number) value).intValue() != 0;
        } else if ("on".equalsIgnoreCase(value.toString())) {
            return true;
        } else {
            return Boolean.parseBoolean(value.toString());
        }
    } else if (Character.class.isAssignableFrom(toType)) {
        final String str = value.toString();
        return (str.length() == 0) ? null : str.charAt(0);
    } else if (Calendar.class.isAssignableFrom(toType)) {
        if (value instanceof Date) {
            final Calendar cal = new GregorianCalendar();
            cal.setTime((Date) value);
            return cal;
        }
    } else if (Date.class.isAssignableFrom(toType)) {
        if (value instanceof Calendar) {
            final long millis = ((Calendar) value).getTimeInMillis();
            try {
                return ConstructorUtils.invokeConstructor(toType, millis);
            } catch (final Exception e) {
                throw new IllegalStateException(e);
            }
        }
    } else if (Enum.class.isAssignableFrom(toType)) {
        Object ret;
        try {
            ret = Enum.valueOf(toType, value.toString());
        } catch (final Exception e) {
            ret = null;
        }
        if (ret == null) {
            Object[] possible;
            try {
                possible = (Object[]) toType.getMethod("values").invoke(null);
            } catch (final Exception e) {
                throw new IllegalStateException(
                        "Couldn't invoke the 'values' method for enum " + toType.getName());
            }
            if (StringValuedEnum.class.isAssignableFrom(toType)) {
                final String test = coerce(String.class, value);
                for (final Object item : possible) {
                    if (((StringValuedEnum) item).getValue().equals(test)) {
                        ret = item;
                        break;
                    }
                }
            } else if (IntValuedEnum.class.isAssignableFrom(toType)) {
                final int test = coerce(Integer.TYPE, value);
                for (final Object item : possible) {
                    if (((IntValuedEnum) item).getValue() == test) {
                        ret = item;
                        break;
                    }
                }
            } else {
                throw new ConversionException("Invalid enum: " + value);
            }
        }
        return ret;
    } else if (Entity.class.isAssignableFrom(toType)) {
        final Long id = coerce(Long.class, value);
        return EntityHelper.reference(toType, id);
    } else if (Locale.class.isAssignableFrom(toType)) {
        return LocaleConverter.instance().valueOf(value.toString());
    } else if (Collection.class.isAssignableFrom(toType)) {
        final Collection collection = (Collection) ClassHelper.instantiate(toType);
        final Iterator iterator = IteratorUtils.getIterator(value);
        while (iterator.hasNext()) {
            collection.add(iterator.next());
        }
        return collection;
    } else if (toType.isArray()) {
        final Collection collection = coerceCollection(toType.getComponentType(), value);
        final Object[] array = (Object[]) Array.newInstance(toType.getComponentType(), collection.size());
        return collection.toArray(array);
    }

    // We don't know how to convert the value
    throw new ConversionException("Cannot coerce value to: " + toType.getName());
}

From source file:com.wrmsr.search.dsl.util.DerivedSuppliers.java

private static void unboxValue(BytecodeBlock body, Class<?> clazz) {
    if (clazz == boolean.class) {
        body.invokeVirtual(Boolean.class, "booleanValue", boolean.class);
    } else if (clazz == byte.class) {
        body.invokeVirtual(Byte.class, "byteValue", byte.class);
    } else if (clazz == short.class) {
        body.invokeVirtual(Short.class, "shortValue", short.class);
    } else if (clazz == int.class) {
        body.invokeVirtual(Integer.class, "intValue", int.class);
    } else if (clazz == long.class) {
        body.invokeVirtual(Long.class, "longValue", long.class);
    } else if (clazz == float.class) {
        body.invokeVirtual(Float.class, "floatValue", float.class);
    } else if (clazz == double.class) {
        body.invokeVirtual(Double.class, "doubleValue", double.class);
    } else {//from  www  .  j  a  v  a2s  .com
        checkState(!clazz.isPrimitive());
    }
}

From source file:com.appleframework.core.utils.ClassUtility.java

/**
 * ?primitivewrapper?primitive/*from w w  w . j av a2s .  c  om*/
 * <p>
 * 
 * <p/>
 * <pre>
 * ClassUtil.getPrimitiveWrapperType(int.class) = Integer.class;
 * ClassUtil.getPrimitiveWrapperType(int[].class) = int[].class;
 * ClassUtil.getPrimitiveWrapperType(int[][].class) = int[][].class;
 * ClassUtil.getPrimitiveWrapperType(String[][].class) = String[][].class;
 * </pre>
 * <p/>
 * </p>
 */
@SuppressWarnings("unchecked")
public static <T> Class<T> getWrapperTypeIfPrimitive(Class<T> type) {
    if (type.isPrimitive()) {
        return ((PrimitiveInfo<T>) PRIMITIVES.get(type.getName())).wrapperType;
    }

    return type;
}

From source file:com.tmind.framework.pub.utils.MethodUtils.java

/**
 * <p>Determine whether a type can be used as a parameter in a method invocation.
 * This method handles primitive conversions correctly.</p>
 *
 * <p>In order words, it will match a <code>Boolean</code> to a <code>boolean</code>,
 * a <code>Long</code> to a <code>long</code>,
 * a <code>Float</code> to a <code>float</code>,
 * a <code>Integer</code> to a <code>int</code>,
 * and a <code>Double</code> to a <code>double</code>.
 * Now logic widening matches are allowed.
 * For example, a <code>Long</code> will not match a <code>int</code>.
 *
 * @param parameterType the type of parameter accepted by the method
 * @param parameterization the type of parameter being tested
 *
 * @return true if the assignement is compatible.
 *//*w w w .j a v a  2s  .  co m*/
public static final boolean isAssignmentCompatible(Class parameterType, Class parameterization) {
    // try plain assignment
    if (parameterType.isAssignableFrom(parameterization)) {
        return true;
    }

    if (parameterType.isPrimitive()) {
        // this method does *not* do widening - you must specify exactly
        // is this the right behaviour?
        Class parameterWrapperClazz = getPrimitiveWrapper(parameterType);
        if (parameterWrapperClazz != null) {
            return parameterWrapperClazz.equals(parameterization);
        }
    }

    return false;
}

From source file:com.jeeframework.util.classes.ClassUtils.java

/**
 * Determine if the given type is assignable from the given value,
 * assuming setting by reflection. Considers primitive wrapper classes
 * as assignable to the corresponding primitive types.
 * @param type   the target type//ww  w. ja  v  a  2  s. c om
 * @param value the value that should be assigned to the type
 * @return if the type is assignable from the value
 */
public static boolean isAssignableValue(Class type, Object value) {
    Assert.notNull(type, "Type must not be null");
    return (value != null ? isAssignable(type, value.getClass()) : !type.isPrimitive());
}

From source file:grails.util.GrailsClassUtils.java

/**
 * Returns true if the specified clazz parameter is either the same as, or is a superclass or superinterface
 * of, the specified type parameter. Converts primitive types to compatible class automatically.
 *
 * @param clazz//from   w  w w .  j a  v a  2  s .  c  o  m
 * @param type
 * @return true if the class is a taglib
 * @see java.lang.Class#isAssignableFrom(Class)
 */
public static boolean isAssignableOrConvertibleFrom(Class<?> clazz, Class<?> type) {
    if (type == null || clazz == null) {
        return false;
    }
    if (type.isPrimitive()) {
        // convert primitive type to compatible class
        Class<?> primitiveClass = GrailsClassUtils.PRIMITIVE_TYPE_COMPATIBLE_CLASSES.get(type);
        if (primitiveClass == null) {
            // no compatible class found for primitive type
            return false;
        }
        return clazz.isAssignableFrom(primitiveClass);
    }
    return clazz.isAssignableFrom(type);
}

From source file:com.sparkplatform.api.core.PropertyAsserter.java

/**
 * See {@link #assertBasicGetterSetterBehavior(Object,String)} method. Only difference is that here we accept an
 * explicit argument for the setter method.
 *
 * @param target   the object on which to invoke the getter and setter
 * @param property the property name, e.g. "firstName"
 * @param argument the property value, i.e. the value the setter will be invoked with
 *///  w  w  w  .ja v a 2 s . c om
public static void assertBasicGetterSetterBehavior(Object target, String property, Object argument) {
    try {
        PropertyDescriptor descriptor = new PropertyDescriptor(property, target.getClass());
        Object arg = argument;
        Class type = descriptor.getPropertyType();
        if (arg == null) {
            if (type.isArray()) {
                arg = Array.newInstance(type.getComponentType(), new int[] { TEST_ARRAY_SIZE });
            } else if (type.isEnum()) {
                arg = type.getEnumConstants()[0];
            } else if (TYPE_ARGUMENTS.containsKey(type)) {
                arg = TYPE_ARGUMENTS.get(type);
            } else {
                arg = invokeDefaultConstructorEvenIfPrivate(type);
            }
        }

        Method writeMethod = descriptor.getWriteMethod();
        Method readMethod = descriptor.getReadMethod();

        writeMethod.invoke(target, arg);
        Object propertyValue = readMethod.invoke(target);
        if (type.isPrimitive()) {
            assertEquals(property + " getter/setter failed test", arg, propertyValue);
        } else {
            assertSame(property + " getter/setter failed test", arg, propertyValue);
        }
    } catch (IntrospectionException e) {
        String msg = "Error creating PropertyDescriptor for property [" + property
                + "]. Do you have a getter and a setter?";
        log.error(msg, e);
        fail(msg);
    } catch (IllegalAccessException e) {
        String msg = "Error accessing property. Are the getter and setter both accessible?";
        log.error(msg, e);
        fail(msg);
    } catch (InvocationTargetException e) {
        String msg = "Error invoking method on target";
        log.error(msg, e);
        fail(msg);
    }
}