注意:我發現有關使用IBinder和Binder進行類型轉換的問題,但他們專注於解決問題。我的問題是理解爲什麼演員首先不是非法的。我也嘗試過使用替換類的BlueJ中的相同操作,但使用相同的結構,並且在運行時失敗。爲什麼IBinder和Binder之間的類型轉換不合法?
這裏是包含我認爲應該是非法的演員的代碼。
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「粘合劑」 variabke)的類型變量,然後向下鑄造的IBinder到它的子類是非法。
換句話說,我認爲,這是非法的一般語法: Child =(Child)variableOfTypeParent; //這會傳遞編譯器,但在運行時會得到類轉換異常。
雖然我明白這是合法的: Child =(Child)variableOfTypeParentAssigned2Child; //但這不是這種情況。
不管怎麼說,
希望在這裏優越的頭腦可以扔我一個骨或告訴我在哪裏,我可以對這種鑄造的閱讀起來。
在此先感謝!
編輯:這是我的代碼從BlueJ的:
`接口的IBinder {
}
類粘合劑實現的IBinder {
}
類服務{
}
類本地服務延伸服務{
IBinder b = new LocalBinder();
class LocalBinder extends Binder{
LocalService getService(){
return LocalService.this;
}
}
}
公共類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);
}
}`
謝謝您的回答。但爲什麼如果我這樣做:IBinder b = new IBinder(){//實現接口};然後嘗試LocalService.LocalBinder binder =(LocalService.LocalBinder)b;我得到一個類拋出異常。問題中的代碼只有當它在該方法中時才起作用,當我按照我剛剛描述的方式執行時會失敗。 –
因爲你的'b'不是'LocalService.LocalBinder'!這是一個匿名類,所以你只能將它轉換爲它實現的接口('IBinder')。 – Kayaman
這是否意味着,通過將'b'設置爲匿名類,它不再是LocalService.LocalBinder的兼容類型,因爲LocalService.LocalBinder實現了不同的接口?這是否也意味着在原始問題中,由於'服務'尚未初始化,並且僅僅是一種類型聲明(即IBinder服務;),這種實現/不明確性的缺乏使得LocalService.LocalBinder可以安全地實現它,而不會導致拋出異常?謝謝你的幫助! –