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:it.unibo.alchemist.language.EnvironmentBuilder.java

@SuppressWarnings("unchecked")
private static Object parseAndCreate(final Class<?> clazz, final String val, final Map<String, Object> env,
        final RandomGenerator random)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {
    if (clazz.isAssignableFrom(RandomGenerator.class) && val.equalsIgnoreCase("random")) {
        L.debug("Random detected! Class " + clazz.getSimpleName() + ", param: " + val);
        if (random == null) {
            L.error("Random instatiation required, but RandomGenerator not yet defined.");
        }//from w  w w .j  av  a 2  s.  c  om
        return random;
    }
    if (clazz.isPrimitive() || PrimitiveUtils.classIsWrapper(clazz)) {
        L.debug(val + " is a primitive or a wrapper: " + clazz);
        if ((clazz.isAssignableFrom(Boolean.TYPE) || clazz.isAssignableFrom(Boolean.class))
                && (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("false"))) {
            return Boolean.parseBoolean(val);
        }
        /*
         * If Number is in clazz's hierarchy
         */
        if (PrimitiveUtils.classIsNumber(clazz)) {
            final Optional<Number> num = extractNumber(val);
            if (num.isPresent()) {
                final Optional<Number> castNum = PrimitiveUtils.castIfNeeded(clazz, num.get());
                /*
                 * If method requires Object or unsupported Number, return
                 * what was parsed.
                 */
                return castNum.orElse(num.get());
            }
        }
        if (Character.TYPE.equals(clazz) || Character.class.equals(clazz)) {
            return val.charAt(0);
        }
    }
    if (List.class.isAssignableFrom(clazz) && val.startsWith("[") && val.endsWith("]")) {
        final List<Constructor<List<?>>> l = unsafeExtractConstructors(clazz);
        @SuppressWarnings("rawtypes")
        final List list = tryToBuild(l, new ArrayList<String>(0), env, random);
        final StringTokenizer strt = new StringTokenizer(val.substring(1, val.length() - 1), ",; ");
        while (strt.hasMoreTokens()) {
            final String sub = strt.nextToken();
            final Object o = tryToParse(sub, env, random);
            if (o == null) {
                L.debug("WARNING: list elemnt skipped: " + sub);
            } else {
                list.add(o);
            }
        }
        return list;
    }
    L.debug(val + " is not a primitive: " + clazz + ". Searching it in the environment...");
    final Object o = env.get(val);
    if (o != null && clazz.isInstance(o)) {
        return o;
    }
    if (Time.class.isAssignableFrom(clazz)) {
        return new DoubleTime(Double.parseDouble(val));
    }
    if (clazz.isAssignableFrom(String.class)) {
        L.debug("String detected! Passing " + val + " back.");
        return val;
    }
    L.debug(val + " not found or class not compatible, unable to go further.");
    return null;
}

From source file:com.laidians.utils.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/*from   w w w. j ava 2 s.  c o  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) {
    Assert.notNull(lhsType, "Left-hand side type must not be null");
    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:h2o.common.spring.util.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/*from w w w.  j a  v a  2s  . c om*/
 * @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
 */
@SuppressWarnings("rawtypes")
public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) {
    Assert.notNull(lhsType, "Left-hand side type must not be null");
    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:ClassTree.java

/**
 * Adds a new class and any parent classes that aren't yet part of the tree
 * @param c the class to add//from  w  w  w . j a  v a 2  s  .c  om
 * @return the newly added node.
 */
public DefaultMutableTreeNode addClass(Class<?> c) {
    // add a new class to the tree

    // skip non-class types
    if (c.isInterface() || c.isPrimitive())
        return null;

    // if the class is already in the tree, return its node
    DefaultMutableTreeNode node = findUserObject(c);
    if (node != null)
        return node;

    // class isn't present--first add class parent recursively

    Class<?> s = c.getSuperclass();

    DefaultMutableTreeNode parent;
    if (s == null)
        parent = root;
    else
        parent = addClass(s);

    // add the class as a child to the parent
    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(c);
    model.insertNodeInto(newNode, parent, parent.getChildCount());

    // make node visible
    TreePath path = new TreePath(model.getPathToRoot(newNode));
    tree.makeVisible(path);

    return newNode;
}

From source file:com.dianping.resource.io.util.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/*from   www.  ja v  a 2s .c o m*/
 * @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:com.github.sourjson.SourJson.java

public @CheckForNull <T> T fromJSON(@CheckForNull Object from, Type toType, double version,
        @CheckForNull AnnotatedElement toAnnos, @CheckForNull Object enclosing) throws SourJsonException {
    if (from == null)
        return null;

    Class<?> toClass = GenericTypeReflector.erase(toType);

    TypeAndAnnos info = new TypeAndAnnos(toType, toAnnos);

    if (toClass.isPrimitive()) {
        toClass = SJUtils.PRIMITIVES_TO_WRAPPERS.get(toClass);
        toType = toClass;//from  w  w w  . j a v  a2  s  .  c o  m
    }

    if (from instanceof JSONObject && ((JSONObject) from).containsKey("!type")) {
        String className = (String) ((JSONObject) from).get("!type");
        try {
            info.type = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new SourJsonException("Could not find class " + className);
        }
    }

    return (T) tcache.getTranslater(info, this).deserialize(from, enclosing, version, this);

}

From source file:com.twinsoft.convertigo.engine.admin.services.database_objects.Set.java

protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    Element root = document.getDocumentElement();
    Document post = null;//  w w w  .j a va  2 s  .co  m
    Element response = document.createElement("response");

    try {
        Map<String, DatabaseObject> map = com.twinsoft.convertigo.engine.admin.services.projects.Get
                .getDatabaseObjectByQName(request);

        xpath = new TwsCachedXPathAPI();
        post = XMLUtils.parseDOM(request.getInputStream());
        postElt = document.importNode(post.getFirstChild(), true);

        String objectQName = xpath.selectSingleNode(postElt, "./@qname").getNodeValue();
        DatabaseObject object = map.get(objectQName);

        //         String comment = getPropertyValue(object, "comment").toString();
        //         object.setComment(comment);

        if (object instanceof Project) {
            Project project = (Project) object;

            String objectNewName = getPropertyValue(object, "name").toString();

            Engine.theApp.databaseObjectsManager.renameProject(project, objectNewName);

            map.remove(objectQName);
            map.put(project.getQName(), project);
        }

        BeanInfo bi = CachedIntrospector.getBeanInfo(object.getClass());

        PropertyDescriptor[] propertyDescriptors = bi.getPropertyDescriptors();

        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String propertyName = propertyDescriptor.getName();

            Method setter = propertyDescriptor.getWriteMethod();

            Class<?> propertyTypeClass = propertyDescriptor.getReadMethod().getReturnType();
            if (propertyTypeClass.isPrimitive()) {
                propertyTypeClass = ClassUtils.primitiveToWrapper(propertyTypeClass);
            }

            try {
                String propertyValue = getPropertyValue(object, propertyName).toString();

                Object oPropertyValue = createObject(propertyTypeClass, propertyValue);

                if (object.isCipheredProperty(propertyName)) {

                    Method getter = propertyDescriptor.getReadMethod();
                    String initialValue = (String) getter.invoke(object, (Object[]) null);

                    if (oPropertyValue.equals(initialValue)
                            || DatabaseObject.encryptPropertyValue(initialValue).equals(oPropertyValue)) {
                        oPropertyValue = initialValue;
                    } else {
                        object.hasChanged = true;
                    }
                }

                if (oPropertyValue != null) {
                    Object args[] = { oPropertyValue };
                    setter.invoke(object, args);
                }

            } catch (IllegalArgumentException e) {
            }
        }

        Engine.theApp.databaseObjectsManager.exportProject(object.getProject());
        response.setAttribute("state", "success");
        response.setAttribute("message", "Project have been successfully updated!");
    } catch (Exception e) {
        Engine.logAdmin.error("Error during saving the properties!\n" + e.getMessage());
        response.setAttribute("state", "error");
        response.setAttribute("message", "Error during saving the properties!");
        Element stackTrace = document.createElement("stackTrace");
        stackTrace.setTextContent(e.getMessage());
        root.appendChild(stackTrace);
    } finally {
        xpath.resetCache();
    }

    root.appendChild(response);
}

From source file:de.matzefratze123.heavyspleef.commands.base.CommandManagerService.java

private Object getDefaultPrimitiveValue(Class<?> clazz) {
    if (!clazz.isPrimitive()) {
        return null;
    }//w w w.  j a  v a2 s  . c  o  m

    Object value = null;

    if (clazz == int.class || clazz == long.class || clazz == short.class || clazz == byte.class
            || clazz == double.class || clazz == float.class) {
        value = 0;
    } else if (clazz == boolean.class) {
        value = false;
    }

    return value;
}

From source file:com.opensymphony.able.introspect.PropertyInfo.java

/**
 * Returns true if the type of the property is a numeric type
 */// w ww.ja v a 2  s.c  om
public boolean isNumber() {
    Class<?> type = getPropertyType();
    return Number.class.isAssignableFrom(type)
            || (type.isPrimitive() && type != boolean.class && type != char.class);
}

From source file:com.sinosoft.one.data.jade.rowmapper.DefaultRowMapperFactory.java

public RowMapper getRowMapper(Class<?> rowType) {

    // BUGFIX: SingleColumnRowMapper ?  Primitive Type 
    if (rowType.isPrimitive()) {
        rowType = ClassUtils.primitiveToWrapper(rowType);
    }/*  w  w w .jav a2s .co  m*/

    // ?  RowMapper
    RowMapper rowMapper;

    // ?(?2Map)
    if (TypeUtils.isColumnType(rowType)) {
        rowMapper = new SingleColumnRowMapper(rowType);
    }
    // Bean??????
    else {
        if (rowType == Map.class) {
            rowMapper = new ColumnMapRowMapper();
        } else if (rowType.isArray()) {
            rowMapper = new ArrayRowMapper(rowType);
        } else if ((rowType == List.class) || (rowType == Collection.class) || (rowType == Set.class)) {
            rowMapper = null;
        } else {
            boolean checkColumns = false;
            boolean checkProperties = false;
            String key = rowType.getName() + "[checkColumns=" + checkColumns + "&checkProperties="
                    + checkProperties + "]";
            rowMapper = rowMappers.get(key);
            if (rowMapper == null) {
                rowMapper = new BeanPropertyRowMapper(rowType, checkColumns, checkProperties); // jade's BeanPropertyRowMapper here
                rowMappers.put(key, rowMapper);
            }
        }
    }
    if (rowMapper == null) {
        throw new IllegalArgumentException();
    }
    return rowMapper;
}