I am trying to use Class.cast () to convert a boxed Double to the primitive double:
Object d = 1.0d;
Class<?> clazz = double.class;
//the bellow line throws java.lang.ClassCastException:
//Cannot cast java.lang.Double to double
clazz.cast(d);
I am doing this because in some part of my code, a value object and a Class are given dynamically, and I do have the guarantee that the value object is of the compatible type. But this exception really confuses me. What is the contract of using cast () ?
UPDATE I ran into this because we have code like:
interface Provider <T> {
T get ();
Class<T> getClazz();
}
//a special handling for double primitive
class DoubleProvider implements Provider<Double> {
public double getDouble(){
return 1.0d;
}
@Override
public Double get() {
return getDouble();
}
@Override
public Class<Double> getClazz() {
//why this actually compiles?
return double.class;
}
}
If double and Double are so different that they are not considered assignable in neither ways, why java allow the getClazz () method in the DoubleProvider to compile? What is the relation between double.class and Double.class?