简体   繁体   English

为什么这段代码会引发ClassCastException?

[英]Why does this code throw a ClassCastException?

The code below is from my App in Android Studio and it runs fine: 下面的代码来自我在Android Studio中的App,它运行良好:

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

I tried to reproduce it like following similar idea: since the original ones: abstract class ViewGroup and ImageView inherit same super class View and its method getParent() returns an interface reference. 我试图按照类似的想法重现它:由于原始想法:抽象类ViewGroupImageView继承了相同的超类View并且其方法getParent()返回接口引用。 Using IntelliJ IDEA I made a similar reproduction for casting purposes in the following code: 使用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);
    }
}

Exception in thread "main" java.lang.ClassCastException: View$$Lambda$1/1078694789 cannot be cast to ViewGroup. 线程“主”中的异常java.lang.ClassCastException:无法将View $$ Lambda $ 1/1078694789强制转换为ViewGroup。

EDITED: The original class View in Android SDK is actually returning a ViewParent so how it's possible? 编辑: Android SDK中的原始类View实际上正在返回ViewParent这怎么可能?

在此处输入图片说明 在此处输入图片说明

Why I'm getting a ClassCastException? 为什么我收到ClassCastException?

both ViewGroup and ImageView are subclasses of View but they have no direct inheritence relationship (super-sub classes). ViewGroupImageView都是View子类,但是它们没有直接的继承关系(超级子类)。 One cannot cast between two subclasses. 一个不能在两个子类之间转换。 only between super class and its sub class (either up casting or down casting) 仅在超类及其子类之间(上铸造或下铸造)

assuming the hierarchy tree is given (meaning you can't change it) then to make this work you need to explicitly ask on the type of the getParent() return value 假设给出了层次结构树(这意味着您无法更改它),那么要进行此工作,您需要明确询问getParent()返回值的类型

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

This will make getParent() return an instance of ViewGroup hence its implementation with ParentView Interface makes ViewGroup compatible then no ClassCastException . 这将使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