In below program I fail to understand why there is ClassCastException
for cast from int.class
Update:
I should specify I know what primitive types are. What I don't understand is why int.class is provided with broken implementation?
public static void main(String[] args) {
System.out.println(DataType.INT.getValue(Integer.class));
System.out.println(DataType.INT.getValue(int.class));//Class cast exception here
}
enum DataType {
INT {
@Override
public <T> T getValue(Class<T> toClass) {
return toClass.cast(1000);//ClassCastException here for int.class
}
};
public abstract <T> T getValue(Class<T> toClass);
}
A class cast exception is thrown by Java when you try to cast an Object of one data type to another. Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.
Class ClassCastException Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException : Object x = new Integer(0); System.
ClassCast Exception is thrown when we try to cast an object of the parent class to the child class object.
This happens because cast()
operation of Class
uses isInstance() method which returns false for primitive classes
.
If this Class object represents a primitive type, this method returns false.
Code for cast()
method is below
public T cast(Object obj) {
if (obj != null && !isInstance(obj))//It fails here since isInstance returns false
throw new ClassCastException();
return (T) obj;
Ok, after going through some links, and trying out some code, I found out that: -
int.class
== Integer.TYPE
== intint.class
!= Integer.class
So, the value of int.class
is Class object representing the type int
.
So, when you invoke your DataType.INT
with int.class
, the toClass
containts int
, on which you cannot invoke cast
. May be because it does not extend from Object
class. Because, cast
method internally uses isinstance
to check whether the invoking type is an Object
type or not.
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException();
return (T) obj;
}
So, if the type that invokes cast
is not an instance of Object
, which of course primitive
types are not, it will return false
, and hence a ClassCastException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With