簡體   English   中英

為什么這段代碼會引發ClassCastException?

[英]Why does this code throw a ClassCastException?

下面的代碼來自我在Android Studio中的App,它運行良好:

static void removeViewParent(ImageView image) {
    if (image.getParent() != null) ((ViewGroup) image.getParent()).removeView(image);
}

我試圖按照類似的想法重現它:由於原始想法:抽象類ViewGroupImageView繼承了相同的超類View並且其方法getParent()返回接口引用。 使用IntelliJ IDEA,我在以下代碼中出於鑄造目的進行了類似的復制:

interface ViewParent {
    ViewParent getParentView();
}

class View {
    ViewParent getParent() {
        return () -> null;
    }
}

abstract class ViewGroup extends View implements ViewParent {
    void removeView(ImageView image) {
        System.out.println(image); //Just for debugging.
    }
}

class ImageView extends View {
}

class RunMain {
    public static void main(String[] args) {
        ImageView image = new ImageView();
        ((ViewGroup) image.getParent()).removeView(image);
    }
}

線程“主”中的異常java.lang.ClassCastException:無法將View $$ Lambda $ 1/1078694789強制轉換為ViewGroup。

編輯: Android SDK中的原始類View實際上正在返回ViewParent這怎么可能?

在此處輸入圖片說明 在此處輸入圖片說明

為什么我收到ClassCastException?

ViewGroupImageView都是View子類,但是它們沒有直接的繼承關系(超級子類)。 一個不能在兩個子類之間轉換。 僅在超類及其子類之間(上鑄造或下鑄造)

假設給出了層次結構樹(這意味着您無法更改它),那么要進行此工作,您需要明確詢問getParent()返回值的類型

if (image.getParent() != null && image.getParent() instanceof ViewGroup) { 
   ((ViewGroup) image.getParent()).removeView(image);
}

這將使getParent()返回ViewGroup的實例,因此其與ParentView Interface的實現使ViewGroup兼容,因此沒有ClassCastException

class View {
    ViewParent getParent() {
        return new ViewGroup() {
            @Override
            public ViewParent getParentView() {
                return null;
            }
        };
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM