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
。
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
来判断。当然,如果你自己清楚,也可以不判断。如果不小心搞错了类似,会抛
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 usejava.lang.ClassCastException
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)🎜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
Isn’t it very clear in the code? What is returned is: return asyncDrawable.getBitmapWorkerTask();