public T cast(Object obj);
Casts an object to the class or interface represented
解釋的比較籠統,意思就是將一個對象裝換為類或者接口。
/**
* Created by shengke on 2016/10/22.
*/
class A {
public static void show() {
System.out.println("Class A show() function");
}
}
class B extends A {
public static void show() {
System.out.println("Class B show() function");
}
}
public class TestCast {
public static void main(String[] args) {
TestCast cls = new TestCast();
Class c = cls.getClass();
System.out.println(c);
Object obj = new A();
B b1 = new B();
b1.show();
// casts object
A a = new A();
a = A.class.cast(b1);
System.out.println(obj.getClass());
System.out.println(b1.getClass());
System.out.println(a.getClass());
}
}
執行結果
class com.scot.effective.genericity.TestCast Class B show() function class com.scot.effective.genericity.A class com.scot.effective.genericity.B class com.scot.effective.genericity.B
核心為:a = A.class.cast(b1); 把a轉化為了B類型,此處容易產生把b1轉成A類型誤解。
/**
* Casts an object to the class or interface represented
* by this {@code Class} 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(cannotCastMsg(obj));
return (T) obj;
}
此方法只能轉換當前類型或其子類下的對象,只是簡單進行強轉。