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>
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!