注意:我发现了有关使用 IBinder 和 Binder 进行类型转换的问题,但它们专注于解决问题。我的问题是首先要理解为什么演员表不是非法的。我还尝试在 BlueJ 中使用替换类进行相同的操作,但使用相同的结构,但在运行时失败。
这是包含我认为应该是非法的演员的代码。
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalService.LocalBinder binder = (LocalService.LocalBinder) service; //<------------ this cast right here. Note that LocalBinder extends Binder which implements the IBinder interface
mService = binder.getService();
mBound = true;
}
我认为将 IBinder(服务变量)父类变量分配给 IBinder 子类的类型化变量(即 LocalService.LocalBinder 'binder' variabke),然后将 IBinder 向下转换为其子类是非法的。
换句话说,我认为在一般语法中这是非法的: Child = (Child) variableOfTypeParent; //这通过了编译器,但在运行时获得了类转换异常。
虽然我确实理解这是合法的: Child = (Child) variableOfTypeParentAssigned2Child; //但这不是这里的情况。
希望这里的高人可以给我一根骨头,或者告诉我在哪里可以阅读这种类型的选角。
编辑:这是我来自 BlueJ 的代码:
interface IBinder {
}
class Binder implements IBinder{
}
class Service{
}
class LocalService extends Service {
IBinder b = new LocalBinder();
class LocalBinder extends Binder{
LocalService getService(){
return LocalService.this;
}
}
}
public class BindingTheIsh {
public void tester(IBinder service) {
**LocalService.LocalBinder binder = (LocalService.LocalBinder) service;** // <-- this line fails at run-time
}
public static void main(String[] args) {
IBinder iBinder = new IBinder(){
};
BindingTheIsh b = new BindingTheIsh();
b.tester(iBinder);
}
}