Java Class.cast方法,javaclass.cast方法

來源:互聯網
上載者:User

Java Class.cast方法,javaclass.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.TestCastClass B show() functionclass com.scot.effective.genericity.Aclass com.scot.effective.genericity.Bclass 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、總結

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




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.