android - java强制类型转换.
PHP中文网
PHP中文网 2017-04-17 17:28:43
0
3
945

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

PHP中文网
PHP中文网

认证0级讲师

reply all(3)
巴扎黑

Methods defined in subclasses and variables of the parent type (still called parent class references) cannot be called. If called, a compilation error will occur.

If the object is indeed a subclass object (see which one is new), you can force the parent class reference to a subclass reference, and then you can call the subclass method. new 的是哪个),那可以将父类引用强制转换为子类引用,之后就可以调用子类方法了。

但是这种转换是有风险的,除非你清楚的知道这个父类引用所引用的对象是子类对象,所以可以先用 instanceof 来判断。当然,如果你自己清楚,也可以不判断。

如果不小心搞错了类似,会抛 java.lang.ClassCastException

But this conversion is risky, unless you clearly know that the object referenced by this parent class reference is a subclass object, so you can use instanceof to judge first. Of course, if you know it yourself, you don’t have to judge. 🎜 🎜If you accidentally make a mistake, java.lang.ClassCastException will be thrown (runtime, not compile time)🎜
class A {
    public void Do1() {
        
    }
}

class B extends A {
    public void Do2() {
        
    }
}

public class Test {
    public static void main(String[] args) {
        A a = new B();
        a.Do2();        // 错误: 找不到符号
        ((B) a).Do2();  // 成功
    }
}
巴扎黑

There is judgment ahead if (drawable instanceof AsyncDrawable)

Since if is true, drawable must be AsyncDrawable, and if the forced type conversion fails, an exception will be thrown, and it is impossible to return NULL

Peter_Zhu

Isn’t it very clear in the code? What is returned is: return asyncDrawable.getBitmapWorkerTask();

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template