Home > Java > javaTutorial > 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
Release: 2024-11-02 05:34:30
Original
451 people have browsed it

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());
Copy after login

which prints:

java.lang.Integer, false
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template