Java中两种Object转int方式的差异及报错原因咨询
(int) o Works But int.class.cast(o) Throws ClassCastException Great question—this touches on some tricky details about Java's primitive types, wrapper classes, and how casting operates at compile vs runtime. Let's break it down step by step:
1. What's happening with (int) o?
First, remember that when you write Object o = 1;, Java automatically boxes the primitive int value 1 into an Integer object (this is compiler-level syntactic sugar).
When you cast (int) o, the compiler does two helpful things behind the scenes:
- It first casts the
ObjectreferenceotoInteger(since it can infer the underlying object type here). - Then it automatically unboxes the
Integerto its corresponding primitiveintvalue, effectively running((Integer) o).intValue().
This works smoothly because the compiler handles the unboxing step for you—this is part of Java's autoboxing/unboxing feature introduced in Java 5.
2. Why does int.class.cast(o) fail?
Let's clarify what int.class represents: it's the Class object for the primitive type int, not the wrapper class Integer.
The Class.cast(Object obj) method is built for reference type conversions only. It checks if the input object can be cast to the type represented by the Class instance, but it has no logic to handle autoboxing or unboxing between primitives and their wrappers.
When you call int.class.cast(o), the JVM tries to cast the Integer object directly to the primitive int type—but primitives aren't reference types, so this isn't a valid reference conversion. Hence, you get the ClassCastException saying you can't cast java.lang.Integer to int.
Key Differences Recap
(int) ois a compile-time cast that leverages autounboxing: the compiler translates it into a cast to the wrapper class followed by an unboxing call.Class.cast()is a runtime-only operation that only handles reference type conversions. It doesn't support converting between wrapper objects and primitive values, so using it withint.class(a primitive type'sClassobject) will fail when given anIntegerobject.
As a quick side note: if you used Integer.class.cast(o) instead, that would work (it would return the Integer object), and you could then unbox it to int manually or via another cast like (int) Integer.class.cast(o).
内容的提问来源于stack exchange,提问作者Luke Taylor

