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.crazydog.util.spring.ClassUtils.java

/**
 * Check if the right-hand side type may be assigned to the left-hand side
 * type, assuming setting by reflection. Considers primitive wrapper
 * classes as assignable to the corresponding primitive types.
 * @param lhsType the target type/* w  ww.  j a  v  a 2s .co m*/
 * @param rhsType the value type that should be assigned to the target type
 * @return if the target type is assignable from the value type
 * @see TypeUtils#isAssignable
 */
public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) {
    org.springframework.util.Assert.notNull(lhsType, "Left-hand side type must not be null");
    org.springframework.util.Assert.notNull(rhsType, "Right-hand side type must not be null");
    if (lhsType.isAssignableFrom(rhsType)) {
        return true;
    }
    if (lhsType.isPrimitive()) {
        Class<?> resolvedPrimitive = primitiveWrapperTypeMap.get(rhsType);
        if (resolvedPrimitive != null && lhsType.equals(resolvedPrimitive)) {
            return true;
        }
    } else {
        Class<?> resolvedWrapper = primitiveTypeToWrapperMap.get(rhsType);
        if (resolvedWrapper != null && lhsType.isAssignableFrom(resolvedWrapper)) {
            return true;
        }
    }
    return false;
}

From source file:it.larusba.neo4j.jdbc.http.HttpResultSet.java

@Override
public String getString(int columnIndex) throws SQLException {
    String object = null;//from w w  w.j  a v  a 2  s  . c o  m

    checkClosed();
    Object value = get(columnIndex);

    if (value != null) {
        final Class<?> type = value.getClass();

        if (String.class.equals(type)) {
            object = (String) value;
        } else {
            if (type.isPrimitive() || Number.class.isAssignableFrom(type)) {
                object = value.toString();
            } else {
                try {
                    object = OBJECT_MAPPER.writeValueAsString(value);
                } catch (Exception e) {
                    throw new SQLException("Couldn't convert value " + value + " of type " + type + " to JSON "
                            + e.getMessage());
                }
            }
        }
    }
    return object;
}

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

/**
 * <p>Clone an object.</p>//from   w w w  .ja  v a 2 s  . c o m
 *
 * @param <T> the type of the object
 * @param obj  the object to clone, null returns null
 * @return the clone if the object implements {@link Cloneable} otherwise {@code null}
 * @throws CloneFailedException if the object is cloneable and the clone operation fails
 * @since 3.0
 */
public static <T> T clone(final T obj) {
    if (obj instanceof Cloneable) {
        final Object result;
        if (obj.getClass().isArray()) {
            final Class<?> componentType = obj.getClass().getComponentType();
            if (!componentType.isPrimitive()) {
                result = ((Object[]) obj).clone();
            } else {
                int length = Array.getLength(obj);
                result = Array.newInstance(componentType, length);
                while (length-- > 0) {
                    Array.set(result, length, Array.get(obj, length));
                }
            }
        } else {
            try {
                final Method clone = obj.getClass().getMethod("clone");
                result = clone.invoke(obj);
            } catch (final NoSuchMethodException e) {
                throw new CloneFailedException(
                        "Cloneable type " + obj.getClass().getName() + " has no clone method", e);
            } catch (final IllegalAccessException e) {
                throw new CloneFailedException("Cannot clone Cloneable type " + obj.getClass().getName(), e);
            } catch (final InvocationTargetException e) {
                throw new CloneFailedException("Exception cloning Cloneable type " + obj.getClass().getName(),
                        e.getCause());
            }
        }
        @SuppressWarnings("unchecked")
        final T checked = (T) result;
        return checked;
    }

    return null;
}

From source file:fr.inria.atlanmod.instantiator.SpecimenGenerator.java

private Object nextValue(Class<?> instanceClass) {
    final Object value;
    if (instanceClass.isPrimitive() || Primitives.isWrapperType(instanceClass)) {
        value = nextPrimitive(Primitives.unwrap(instanceClass));
    } else {/*from   ww w  . j av  a 2s .  co  m*/
        value = nextObject(instanceClass);
    }
    // System.out.println(value);
    return value;
}

From source file:com.medallia.tiny.ObjectProvider.java

/**
 * Get an object by annotation//from  w ww . j  a va 2s  .  c o  m
 */
@SuppressWarnings("unchecked")
public <X> X getByAnnotation(Class<? extends Annotation> annotation, Class<X> c) {
    Object o = annotationMap.get(annotation);
    if (o == null)
        LOG.warn("No object for annotation " + annotation + " in " + this);

    //      We do a safe cast if possible here, since we do not know what type of object was used when registering
    return c.isPrimitive() ? (X) o : c.cast(o);
}

From source file:com.espertech.esperio.csv.CSVInputAdapter.java

private Map<String, Object> constructPropertyTypes(String eventTypeName, Map<String, Object> propertyTypesGiven,
        EventAdapterService eventAdapterService) {
    Map<String, Object> propertyTypes = new HashMap<String, Object>();
    EventType eventType = eventAdapterService.getExistsTypeByName(eventTypeName);
    if (eventType == null) {
        if (propertyTypesGiven != null) {
            eventAdapterService.addNestableMapType(eventTypeName,
                    new HashMap<String, Object>(propertyTypesGiven), null, true, true, true, false, false);
        }/*from w  w  w. j  a v a  2 s.c  o m*/
        return propertyTypesGiven;
    }
    if (!eventType.getUnderlyingType().equals(Map.class)) {
        beanClass = eventType.getUnderlyingType();
    }
    if (propertyTypesGiven != null && eventType.getPropertyNames().length != propertyTypesGiven.size()) {
        // allow this scenario for beans as we may want to bring in a subset of properties
        if (beanClass != null) {
            return propertyTypesGiven;
        } else {
            throw new EPException("Event type " + eventTypeName
                    + " has already been declared with a different number of parameters");
        }
    }
    for (String property : eventType.getPropertyNames()) {
        Class type;
        try {
            type = eventType.getPropertyType(property);
        } catch (PropertyAccessException e) {
            // thrown if trying to access an invalid property on an EventBean
            throw new EPException(e);
        }
        if (propertyTypesGiven != null && propertyTypesGiven.get(property) == null) {
            throw new EPException(
                    "Event type " + eventTypeName + "has already been declared with different parameters");
        }
        if (propertyTypesGiven != null && !propertyTypesGiven.get(property).equals(type)) {
            throw new EPException("Event type " + eventTypeName
                    + "has already been declared with a different type for property " + property);
        }
        // we can't set read-only properties for bean
        if (!eventType.getUnderlyingType().equals(Map.class)) {
            PropertyDescriptor[] pds = ReflectUtils.getBeanProperties(beanClass);
            PropertyDescriptor pd = null;
            for (PropertyDescriptor p : pds) {
                if (p.getName().equals(property))
                    pd = p;
            }
            if (pd == null) {
                continue;
            }
            if (pd.getWriteMethod() == null) {
                if (propertyTypesGiven == null) {
                    continue;
                } else {
                    throw new EPException(
                            "Event type " + eventTypeName + "property " + property + " is read only");
                }
            }
        }
        propertyTypes.put(property, type);
    }

    // flatten nested types
    Map<String, Object> flattenPropertyTypes = new HashMap<String, Object>();
    for (String p : propertyTypes.keySet()) {
        Object type = propertyTypes.get(p);
        if (type instanceof Class && ((Class) type).getName().equals("java.util.Map")
                && eventType instanceof MapEventType) {
            MapEventType mapEventType = (MapEventType) eventType;
            Map<String, Object> nested = (Map) mapEventType.getTypes().get(p);
            for (String nestedProperty : nested.keySet()) {
                flattenPropertyTypes.put(p + "." + nestedProperty, nested.get(nestedProperty));
            }
        } else if (type instanceof Class) {
            Class c = (Class) type;
            if (!c.isPrimitive() && !c.getName().startsWith("java")) {
                PropertyDescriptor[] pds = ReflectUtils.getBeanProperties(c);
                for (PropertyDescriptor pd : pds) {
                    if (pd.getWriteMethod() != null)
                        flattenPropertyTypes.put(p + "." + pd.getName(), pd.getPropertyType());
                }
            } else {
                flattenPropertyTypes.put(p, type);
            }
        } else {
            flattenPropertyTypes.put(p, type);
        }
    }
    return flattenPropertyTypes;
}

From source file:br.gov.frameworkdemoiselle.internal.configuration.ConfigurationLoader.java

private <T> Object getBasic(String key, Class<T> fieldClass,
        org.apache.commons.configuration.Configuration config) {
    Object value = null;//from   w  w  w. j  a  v a 2  s .c  om

    try {
        Method method;
        String methodName = "get" + Strings.firstToUpper(fieldClass.getSimpleName());

        if (!fieldClass.isPrimitive()) {
            method = config.getClass().getMethod(methodName, String.class, fieldClass);
            value = method.invoke(config, key, null);
        } else if (config.containsKey(key)) {
            method = config.getClass().getMethod(methodName, String.class);
            value = method.invoke(config, key);
        }

    } catch (Throwable cause) {
        throw new ConfigurationException(bundle.getString("error-converting-to-type", fieldClass.getName()),
                cause);
    }

    return value;
}

From source file:org.neo4j.jdbc.http.HttpResultSet.java

@Override
public String getString(int columnIndex) throws SQLException {

    String object = null;//  w ww. jav  a2 s .  com

    checkClosed();
    Object value = get(columnIndex);

    if (value != null) {
        final Class<?> type = value.getClass();

        if (String.class.equals(type)) {
            object = (String) value;
        } else {
            if (type.isPrimitive() || Number.class.isAssignableFrom(type)) {
                object = value.toString();
            } else {
                try {
                    object = OBJECT_MAPPER.writeValueAsString(value);
                } catch (Exception e) {
                    throw new SQLException("Couldn't convert value " + value + " of type " + type + " to JSON "
                            + e.getMessage());
                }
            }
        }
    }
    return object;
}

From source file:com.gdcn.modules.db.jdbc.processor.CamelBeanProcessor.java

/**
 * Convert a <code>ResultSet</code> column into an object.  Simple
 * implementations could just call <code>rs.getObject(index)</code> while
 * more complex implementations could perform type manipulation to match
 * the column's type to the bean property type.
 *
 * <p>//from  w ww.  j av a2s.  c  o  m
 * This implementation calls the appropriate <code>ResultSet</code> getter
 * method for the given property type to perform the type conversion.  If
 * the property type doesn't match one of the supported
 * <code>ResultSet</code> types, <code>getObject</code> is called.
 * </p>
 *
 * @param rs The <code>ResultSet</code> currently being processed.  It is
 * positioned on a valid row before being passed into this method.
 *
 * @param index The current column index being processed.
 *
 * @param propType The bean property type that this column needs to be
 * converted into.
 *
 * @throws SQLException if a database access error occurs
 *
 * @return The object from the <code>ResultSet</code> at the given column
 * index after optional type processing or <code>null</code> if the column
 * value was SQL NULL.
 */
protected Object processColumn(ResultSet rs, int index, Class<?> propType) throws SQLException {

    if (!propType.isPrimitive() && rs.getObject(index) == null) {
        return null;
    }

    if (propType.equals(String.class)) {
        return rs.getString(index);

    } else if (propType.equals(Integer.TYPE) || propType.equals(Integer.class)) {
        return Integer.valueOf(rs.getInt(index));

    } else if (propType.equals(Boolean.TYPE) || propType.equals(Boolean.class)) {
        return Boolean.valueOf(rs.getBoolean(index));

    } else if (propType.equals(Long.TYPE) || propType.equals(Long.class)) {
        return Long.valueOf(rs.getLong(index));

    } else if (propType.equals(Double.TYPE) || propType.equals(Double.class)) {
        return Double.valueOf(rs.getDouble(index));

    } else if (propType.equals(Float.TYPE) || propType.equals(Float.class)) {
        return Float.valueOf(rs.getFloat(index));

    } else if (propType.equals(Short.TYPE) || propType.equals(Short.class)) {
        return Short.valueOf(rs.getShort(index));

    } else if (propType.equals(Byte.TYPE) || propType.equals(Byte.class)) {
        return Byte.valueOf(rs.getByte(index));

    } else if (propType.equals(Timestamp.class)) {
        return rs.getTimestamp(index);

    } else if (propType.equals(SQLXML.class)) {
        return rs.getSQLXML(index);

    } else {
        return rs.getObject(index);
    }

}

From source file:eu.qualityontime.commons.MethodUtils.java

/**
 * Gets the number of steps required needed to turn the source class into
 * the destination class. This represents the number of steps in the object
 * hierarchy graph.//from   w  w w  . j av  a 2  s .  c  o  m
 * 
 * @param srcClass
 *            The source class
 * @param destClass
 *            The destination class
 * @return The cost of transforming an object
 */
private static float getObjectTransformationCost(Class<?> srcClass, final Class<?> destClass) {
    float cost = 0.0f;
    while (srcClass != null && !destClass.equals(srcClass)) {
        if (destClass.isPrimitive()) {
            final Class<?> destClassWrapperClazz = getPrimitiveWrapper(destClass);
            if (destClassWrapperClazz != null && destClassWrapperClazz.equals(srcClass)) {
                cost += 0.25f;
                break;
            }
        }
        if (destClass.isInterface() && isAssignmentCompatible(destClass, srcClass)) {
            // slight penalty for interface match.
            // we still want an exact match to override an interface match,
            // but
            // an interface match should override anything where we have to
            // get a
            // superclass.
            cost += 0.25f;
            break;
        }
        cost++;
        srcClass = srcClass.getSuperclass();
    }

    /*
     * If the destination class is null, we've travelled all the way up to
     * an Object match. We'll penalize this by adding 1.5 to the cost.
     */
    if (srcClass == null) {
        cost += 1.5f;
    }

    return cost;
}