java强制类型转换.

android training中的bitmap讲解中有这么一段代码

static class AsyncDrawable extends BitmapDrawable {

    private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;


    public AsyncDrawable(Resources res, Bitmap bitmap,

            BitmapWorkerTask bitmapWorkerTask) {

        super(res, bitmap);

        bitmapWorkerTaskReference =

            new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);

    }


    public BitmapWorkerTask getBitmapWorkerTask() {

        return bitmapWorkerTaskReference.get();

    }

}

----------------------

private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {

   if (imageView != null) {

       final Drawable drawable = imageView.getDrawable();

       if (drawable instanceof AsyncDrawable) {

           final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;

           return asyncDrawable.getBitmapWorkerTask();

       }

    }

    return null;

}

这里的drawable强制转换为AsyncDrawable,为什么这里的父类转换为子类asyncDrawable.getBitmapWorkerTask()不是返回null

慕码人2483693
浏览 501回答 3
3回答

德玛西亚99

子类中定义的方法,父类型的变量(还是叫父类引用顺口)是不能调用的,如果调用会引发编译错误。如果对象确实是子类对象(看&nbsp;new&nbsp;的是哪个),那可以将父类引用强制转换为子类引用,之后就可以调用子类方法了。但是这种转换是有风险的,除非你清楚的知道这个父类引用所引用的对象是子类对象,所以可以先用&nbsp;instanceof来判断。当然,如果你自己清楚,也可以不判断。如果不小心搞错了类似,会抛&nbsp;java.lang.ClassCastException(运行时,非编译时)class A {&nbsp; &nbsp; public void Do1() {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }}class B extends A {&nbsp; &nbsp; public void Do2() {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }}public class Test {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; A a = new B();&nbsp; &nbsp; &nbsp; &nbsp; a.Do2();&nbsp; &nbsp; &nbsp; &nbsp; // 错误: 找不到符号&nbsp; &nbsp; &nbsp; &nbsp; ((B) a).Do2();&nbsp; // 成功&nbsp; &nbsp; }}

慕虎7371278

前面有判断&nbsp;if (drawable instanceof AsyncDrawable)既然if为true,drawable 就肯定是 AsyncDrawable,而且强制类型转换失败会抛异常,也不可能返回NULL

jeck猫

代码里不是很清楚吗,返回的是:return asyncDrawable.getBitmapWorkerTask();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java