Java Class.cast方法


1、Java api

public T cast(Object obj);

Casts an object to the class or interface represented

解釋的比較籠統,意思就是將一個對象裝換為類或者接口。

2、代碼示例

/**
 * 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類型誤解。

3、源碼

    /**
     * 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;
    }

4、總結

此方法只能轉換當前類型或其子類下的對象,只是簡單進行強轉。





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM