public T cast(Object obj)
將對象轉換為此 Class 對象表示的類或接口。若對象非 null 且非目標類型實例,拋出
ClassCastException。
class A { public static void show() { System.out.println("A.show()"); } }
class B extends A { public static void show() { System.out.println("B.show()"); } }
public class TestCast {
public static void main(String[] args) {
Object obj = new A();
B b1 = new B();
b1.show(); // 輸出:B.show()
A a = new A();
a = A.class.cast(b1); // 核心:將 b1 轉為 A 類型引用
System.out.println(obj.getClass()); // class A
System.out.println(b1.getClass()); // class B
System.out.println(a.getClass()); // class B ← 關鍵!
}
}
B.show() class com.scot.effective.genericity.A class com.scot.effective.genericity.B class com.scot.effective.genericity.B
a = A.class.cast(b1) 真實語義:
b1 轉換為 A 類型對象a 的聲明類型視為 A,實際指向仍是 B 實例a.getClass() 依然返回 Bpublic T cast(Object obj) {
if (obj != null && !isInstance(obj)) // 實例檢查
throw new ClassCastException(cannotCastMsg(obj));
return (T) obj; // 直接強轉
}
Class.cast() 只是語法糖,提供編譯期類型安全,運行期仍遵循多態機制。切勿誤以為能改變對象實際類型。