用class对象来执行类型转换和直接强制类型转换有什么区别?
用class对象来执行类型转换和直接强制类型转换有什么区别?比如Building b=new house();
class<house> housetype=house.class;
house h=housetype.cast(b);
h=(house)b;
请问后两句有什么区别?
能否举例说下用class对象来执行类型转换和直接强制类型转换有什么区别?
什么情况下必须使用class对象进行类型转换而不能直接强制类型转换? --------------------编程问答--------------------
/**
* Casts an object to the class or interface represented
* by this <tt>Class</tt> object.
*
* @param obj the object to be cast
* @return the object after casting, or null if obj is null
*
* @throws ClassCastException if the object is not
* null and is not assignable to the type T.
*
* @since 1.5
*/
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException();
return (T) obj;
}
其实没多大区别。。 --------------------编程问答--------------------
public <T> T cast(Object o, Class<T> clz){
return clz.cast(o);
}
这种情况,你就只能用.cast --------------------编程问答-------------------- 反射运用的场景就是在你不知道实际类型是什么的情况下。如果你都知道要强转成什么类型了那么声明式的强转和反射的强转就没区别了。 --------------------编程问答--------------------
public <T> T cast(Object o, Class<T> clz){
return (T)o;
}
怎么破? --------------------编程问答--------------------
有道理,我破了
补充:Java , Java SE