Home > Java > javaTutorial > body text

How to Determine if an Object Wraps a Primitive Type in Java?

Mary-Kate Olsen
Release: 2024-10-31 20:27:29
Original
925 people have browsed it

How to Determine if an Object Wraps a Primitive Type in Java?

Determining if an Object is Primitive: Using Wrapper Type Detection

In Java, an object can wrap primitive values through auto-boxing. To differentiate between true primitive types and boxed primitives, a specific approach is necessary.

Checking for Primitive Types using Class.isPrimitive()

The Class.isPrimitive() method is not suitable for this purpose. Primitive types are represented as references to their wrapper classes (e.g., Integer object for int).

Alternative Method: Identifying Wrapper Types

The solution lies in determining if an object's type is a wrapper for a primitive type. While Java libraries lack built-in functionality for this, it can be easily implemented:

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

Usage: The provided method isWrapperType takes a Class object as an argument and returns true if it is a wrapper for a primitive type, and false otherwise.

The above is the detailed content of How to Determine if an Object Wraps a Primitive Type 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!