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.example.basedemo.view.ViewInjectorImpl.java

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

    if (handlerType == null || IGNORED.contains(handlerType)) {
        return;//  w  w w. j av a2s  .  c  om
    }

    // ?
    injectObject(handler, handlerType.getSuperclass(), finder);

    // 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 @ViewInject for " + handlerType.getSimpleName()
                                + "." + field.getName());
                    }
                } catch (Throwable ex) {
                    Log.e(ex.getMessage(), ex.toString());
                }
            }
        }
    } // end inject view

    // 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) {
                    Log.e(ex.getMessage(), ex.toString());
                }
            }
        }
    } // end inject event

}

From source file:com.asuka.android.asukaandroid.view.ViewInjectorImpl.java

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

    if (handlerType == null || IGNORED.contains(handlerType)) {
        return;//from w w  w .  j  a va2 s.c o  m
    }

    // ?
    injectObject(handler, handlerType.getSuperclass(), finder);

    // 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 @ViewInject for " + handlerType.getSimpleName()
                                + "." + field.getName());
                    }
                } catch (Throwable ex) {
                    LogUtil.e(ex.getMessage(), ex);
                }
            }
        }
    } // end inject view

    // 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);
                }
            }
        }
    } // end inject event

}

From source file:com.ery.ertc.estorm.util.ClassSize.java

/**
 * The estimate of the size of a class instance depends on whether the JVM uses 32 or 64 bit addresses, that is it depends on the size
 * of an object reference. It is a linear function of the size of a reference, e.g. 24 + 5*r where r is the size of a reference (usually
 * 4 or 8 bytes)./*from  w  ww .ja v a 2 s.  co  m*/
 * 
 * This method returns the coefficients of the linear function, e.g. {24, 5} in the above example.
 * 
 * @param cl
 *            A class whose instance size is to be estimated
 * @param debug
 *            debug flag
 * @return an array of 3 integers. The first integer is the size of the primitives, the second the number of arrays and the third the
 *         number of references.
 */
@SuppressWarnings("unchecked")
private static int[] getSizeCoefficients(Class cl, boolean debug) {
    int primitives = 0;
    int arrays = 0;
    // The number of references that a new object takes
    int references = nrOfRefsPerObj;
    int index = 0;

    for (; null != cl; cl = cl.getSuperclass()) {
        Field[] field = cl.getDeclaredFields();
        if (null != field) {
            for (Field aField : field) {
                if (Modifier.isStatic(aField.getModifiers()))
                    continue;
                Class fieldClass = aField.getType();
                if (fieldClass.isArray()) {
                    arrays++;
                    references++;
                } else if (!fieldClass.isPrimitive()) {
                    references++;
                } else {// Is simple primitive
                    String name = fieldClass.getName();

                    if (name.equals("int") || name.equals("I"))
                        primitives += Bytes.SIZEOF_INT;
                    else if (name.equals("long") || name.equals("J"))
                        primitives += Bytes.SIZEOF_LONG;
                    else if (name.equals("boolean") || name.equals("Z"))
                        primitives += Bytes.SIZEOF_BOOLEAN;
                    else if (name.equals("short") || name.equals("S"))
                        primitives += Bytes.SIZEOF_SHORT;
                    else if (name.equals("byte") || name.equals("B"))
                        primitives += Bytes.SIZEOF_BYTE;
                    else if (name.equals("char") || name.equals("C"))
                        primitives += Bytes.SIZEOF_CHAR;
                    else if (name.equals("float") || name.equals("F"))
                        primitives += Bytes.SIZEOF_FLOAT;
                    else if (name.equals("double") || name.equals("D"))
                        primitives += Bytes.SIZEOF_DOUBLE;
                }
                if (debug) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("" + index + " " + aField.getName() + " " + aField.getType());
                    }
                }
                index++;
            }
        }
    }
    return new int[] { primitives, arrays, references };
}

From source file:net.sourceforge.jaulp.lang.ObjectUtils.java

/**
 * Try to clone the given object.//w ww  .j  a  v  a2 s . c  om
 *
 * @param object
 *            The object to clone.
 * @return The cloned object or null if the clone process failed.
 * @throws NoSuchMethodException
 *             the no such method exception
 * @throws SecurityException
 *             Thrown if the security manager indicates a security violation.
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws ClassNotFoundException
 *             the class not found exception
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Object cloneObject(final Object object)
        throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, ClassNotFoundException, InstantiationException, IOException {
    Object clone = null;
    // Try to clone the object if it implements Serializable.
    if (object instanceof Serializable) {
        clone = SerializedObjectUtils.copySerializedObject((Serializable) object);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object if it is Cloneble.
    if (clone == null && object instanceof Cloneable) {

        if (object.getClass().isArray()) {
            final Class<?> componentType = object.getClass().getComponentType();
            if (componentType.isPrimitive()) {
                int length = Array.getLength(object);
                clone = Array.newInstance(componentType, length);
                while (length-- > 0) {
                    Array.set(clone, length, Array.get(object, length));
                }
            } else {
                clone = ((Object[]) object).clone();
            }
            if (clone != null) {
                return clone;
            }
        }
        Class<?> clazz = object.getClass();
        Method cloneMethod = clazz.getMethod("clone", (Class[]) null);
        clone = cloneMethod.invoke(object, (Object[]) null);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object by copying all his properties with
    // the BeanUtils.copyProperties() method.
    if (clone == null) {
        clone = ReflectionUtils.getNewInstance(object);
        BeanUtils.copyProperties(clone, object);
    }
    return clone;
}

From source file:edu.usu.sdl.openstorefront.util.ReflectionUtil.java

/**
 * This check for Value Model Objects//from   w  ww . ja v a  2 s . c o m
 *
 * @param fieldClass
 * @return
 */
public static boolean isComplexClass(Class fieldClass) {
    Objects.requireNonNull(fieldClass, "Class is required");

    boolean complex = false;
    if (!fieldClass.isPrimitive() && !fieldClass.isArray()
            && !fieldClass.getSimpleName().equalsIgnoreCase(String.class.getSimpleName())
            && !fieldClass.getSimpleName().equalsIgnoreCase(Long.class.getSimpleName())
            && !fieldClass.getSimpleName().equalsIgnoreCase(Integer.class.getSimpleName())
            && !fieldClass.getSimpleName().equalsIgnoreCase(Boolean.class.getSimpleName())
            && !fieldClass.getSimpleName().equalsIgnoreCase(Double.class.getSimpleName())
            && !fieldClass.getSimpleName().equalsIgnoreCase(Float.class.getSimpleName())
            && !fieldClass.getSimpleName().equalsIgnoreCase(BigDecimal.class.getSimpleName())
            && !fieldClass.getSimpleName().equalsIgnoreCase(Date.class.getSimpleName())
            && !fieldClass.getSimpleName().equalsIgnoreCase(List.class.getSimpleName())
            && !fieldClass.getSimpleName().equalsIgnoreCase(Map.class.getSimpleName())
            && !fieldClass.getSimpleName().equalsIgnoreCase(Collection.class.getSimpleName())
            && !fieldClass.getSimpleName().equalsIgnoreCase(Queue.class.getSimpleName())
            && !fieldClass.getSimpleName().equalsIgnoreCase(Set.class.getSimpleName())
            && !fieldClass.getSimpleName().equalsIgnoreCase(BigInteger.class.getSimpleName())) {
        complex = true;
    }
    return complex;
}

From source file:com.mtgi.analytics.aop.BehaviorTrackingAdvice.java

/**
 * marshal the given value to a String.  Only java builtin types,
 * and arrays of those types, are converted; everything else is
 * represented as "[qualified.type.name]" to avoid invoking
 * costly (or buggy) toString() methods.
 *///from w w  w. j a  v a 2s  .c  o m
private static final void logValue(EventDataElement parent, String elementName, Class<?> expectedType,
        Object arg) {
    EventDataElement element = parent.addElement(elementName);
    if (arg == null)
        return;

    Class<?> type = arg.getClass();
    //log the concrete type of the argument if it differs from the expected type (i.e. is a subclass)
    //the primitive type checks avoid logging redundant type info for autoboxed values
    if (type != expectedType && !(expectedType.isPrimitive() || type.isPrimitive()))
        element.add("type", type.getName());

    //TODO: use annotations or some other configuration for custom
    //parameter logging?
    String value = "{object}";
    if (type.isArray()) {
        if (shouldLog(type.getComponentType()))
            value = toStringArray(arg);
    } else {
        if (shouldLog(type))
            value = arg.toString();
    }
    element.setText(value);
}

From source file:de.alpharogroup.lang.ObjectExtensions.java

/**
 * Try to clone the given object.//ww  w . j  a va 2s. co  m
 *
 * @param object
 *            The object to clone.
 * @return The cloned object or null if the clone process failed.
 * @throws NoSuchMethodException
 *             the no such method exception
 * @throws SecurityException
 *             Thrown if the security manager indicates a security violation.
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws ClassNotFoundException
 *             the class not found exception
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Object cloneObject(final Object object)
        throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, ClassNotFoundException, InstantiationException, IOException {
    Object clone = null;
    // Try to clone the object if it implements Serializable.
    if (object instanceof Serializable) {
        clone = SerializedObjectUtils.copySerializedObject((Serializable) object);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object if it is Cloneble.
    if (clone == null && object instanceof Cloneable) {

        if (object.getClass().isArray()) {
            final Class<?> componentType = object.getClass().getComponentType();
            if (componentType.isPrimitive()) {
                int length = Array.getLength(object);
                clone = Array.newInstance(componentType, length);
                while (length-- > 0) {
                    Array.set(clone, length, Array.get(object, length));
                }
            } else {
                clone = ((Object[]) object).clone();
            }
            if (clone != null) {
                return clone;
            }
        }
        final Class<?> clazz = object.getClass();
        final Method cloneMethod = clazz.getMethod("clone", (Class[]) null);
        clone = cloneMethod.invoke(object, (Object[]) null);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object by copying all his properties with
    // the BeanUtils.copyProperties() method.
    if (clone == null) {
        clone = ReflectionUtils.getNewInstance(object);
        BeanUtils.copyProperties(clone, object);
    }
    return clone;
}

From source file:jp.terasoluna.fw.util.ConvertUtil.java

/**
 * <code>value</code>???????
 * ?<code>String</code>????<code>List</code>??
 * ?/*  ww  w .j  ava2s.  c  o  m*/
 * 
 * @param value ??
 * @return ??????????<code>List</code>
 *          ??????<code>value</code>????
 */
public static Object convertPrimitiveArrayToList(Object value) {
    if (value == null) {
        return value;
    }
    Class<?> type = value.getClass().getComponentType();

    // value???????
    if (type == null) {
        return value;
    }

    // ?????????
    if (!type.isPrimitive()) {
        return value;
    }

    List<Object> list = new ArrayList<Object>();

    if (value instanceof boolean[]) {
        for (boolean data : (boolean[]) value) {
            // String???????
            list.add(data);
        }
    } else if (value instanceof byte[]) {
        for (byte data : (byte[]) value) {
            list.add(Byte.toString(data));
        }
    } else if (value instanceof char[]) {
        for (char data : (char[]) value) {
            list.add(Character.toString(data));
        }
    } else if (value instanceof double[]) {
        for (double data : (double[]) value) {
            list.add(Double.toString(data));
        }
    } else if (value instanceof float[]) {
        for (float data : (float[]) value) {
            list.add(Float.toString(data));
        }
    } else if (value instanceof int[]) {
        for (int data : (int[]) value) {
            list.add(Integer.toString(data));
        }
    } else if (value instanceof long[]) {
        for (long data : (long[]) value) {
            list.add(Long.toString(data));
        }
    } else if (value instanceof short[]) {
        for (short data : (short[]) value) {
            list.add(Short.toString(data));
        }
    }
    return list;
}

From source file:asmlib.Type.java

public static Type fromClass(Class<?> c) {
    if (c.isPrimitive()) {
        String name = c.getName().toLowerCase();
        for (String[] typeMapping : primitiveTypeNames) {
            if (typeMapping[0].equals(name))
                return Type.fromBytecode(typeMapping[1]);
        }//from   w  w w  .ja  v a  2s . co  m
        throw new AssertionError("This should never happen");
    }

    String s = c.getName();

    if (s.charAt(0) == '[') {
        // Java troca para um misto entre bytecodeName e commonName para arrays
        return Type.fromBytecode(s.replace('.', '/'));
    }

    return Type.fromCommon(s);
}

From source file:com.hpcloud.util.Serialization.java

/**
 * Returns the {@code node} deserialized to an instance of <T> with the implementation of <T>
 * being selected from the registered targets for the node's root key.
 * //from  w ww.ja v  a2 s . c  o m
 * @throws IllegalArgumentException if {@code node} does not contain a single root key
 * @throws IllegalStateException if no target type has been registered for the {@code node}'s root
 *           key
 * @throws RuntimeException if deserialization fails
 */
public static <T> T fromJson(JsonNode node) {
    Preconditions.checkArgument(node.size() == 1, "The node must contain a single root key: %s", node);

    String rootKey = node.fieldNames().next();
    @SuppressWarnings("unchecked")
    Class<T> targetType = (Class<T>) targetTypes.get(rootKey);
    if (targetType == null)
        throw new IllegalStateException("No target type is registered for the root key " + rootKey);

    if (targetType.isPrimitive() || Primitives.isWrapperType(targetType)) {
        try {
            return rootMapper.reader(targetType).readValue(node);
        } catch (IOException e) {
            throw Exceptions.uncheck(e, "Failed to deserialize json: {}", node);
        }
    } else {
        T object = Injector.getInstance(targetType);
        injectMembers(object, node);
        return object;
    }
}