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

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

DDD
DDDOriginal
2024-11-02 05:34:30347browse

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

Is the Object Primitive?

When working with an array of Objects, it may be necessary to determine whether any of the elements are primitive types. The Class.isPrimitive() method does not provide the expected results for objects, such as in the example:

int i = 3;
Object o = i;

System.out.println(o.getClass().getName() + ", " +
                   o.getClass().isPrimitive());

which prints:

java.lang.Integer, false

The Issue

The issue is that Object[] arrays contain references, not primitives. Therefore, Class.isPrimitive() always returns false for objects, even if they represent primitive values.

A Solution

To determine if an object is a wrapper for a primitive type, there is no built-in library function. However, it is possible to create a custom solution:

<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<Class<?>>();
        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 solution uses a HashSet to store the wrapper types. When checking if a class is a wrapper, the set is used to verify if it contains that class.

The above is the detailed content of How to Determine if an Object is a Wrapper Type for Primitive Values in Java?. 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