Home >Java >javaTutorial >How to Determine if an Object in an Array is a Wrapper Type for a Primitive?

How to Determine if an Object in an Array is a Wrapper Type for a Primitive?

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 10:36:30823browse

How to Determine if an Object in an Array is a Wrapper Type for a Primitive?

How to Identify Primitive Types in an Object Array

In Java, determining if an object is of primitive type using Class.isPrimitive() can be misleading. This is because objects in an array are references to the actual values.

To accurately determine if an object is primitive, we need to check if its type is a wrapper for a primitive type. The JDK doesn't provide a built-in method for this, but we can create a custom one:

<code class="java">import java.util.*;

public class Test {
    public static void main(String[] args) {
        System.out.println(isWrapperType(String.class)); // false
        System.out.println(isWrapperType(Integer.class)); // true
    }

    private static final Set<Class<?>> WRAPPER_TYPES = getWrapperTypes();

    public static boolean isWrapperType(Class<?> clazz) {
        return WRAPPER_TYPES.contains(clazz);
    }

    private static Set<Class<?>> getWrapperTypes() {
        Set<Class<?>> ret = new HashSet<>();
        ret.add(Boolean.class);
        ret.add(Character.class);
        ret.add(Byte.class);
        ret.add(Short.class);
        ret.add(Integer.class);
        ret.add(Long.class);
        ret.add(Float.class);
        ret.add(Double.class);
        ret.add(Void.class);
        return ret;
    }
}</code>

This custom method, isWrapperType(), creates a set of primitive wrapper types and checks if the given class matches any of them. This approach ensures accurate identification of primitive types within an Object[] array.

The above is the detailed content of How to Determine if an Object in an Array is a Wrapper Type for a Primitive?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn