2 回答

TA貢獻1779條經驗 獲得超6個贊
為了將來可能的參考,截至2015 年 9 月,我提出了兩種處理問題的方法。
第一個是從Go代碼返回一個錯誤并在Java 中嘗試/捕獲錯誤。下面是一個例子:
// ExportedGoFunction returns a pointer to a GoStruct or nil in case of fail
func ExportedGoFunction() (*GoStruct, error) {
result := myUnexportedGoStruct()
if result == nil {
return nil, errors.New("Error: GoStruct is Nil")
}
return result, nil
}
然后嘗試/捕獲Java 中的錯誤
try {
GoLibrary.GoStruct myStruct = GoLibrary.ExportedGoFunction();
}
catch (Exception e) {
e.printStackTrace(); // myStruct is nil
}
這種方法既是慣用的Go又是Java,但即使它可以防止程序崩潰,它最終也會使用 try/catch 語句使代碼膨脹,并導致更多的開銷。
因此,基于用戶@SnoProblem回答解決它的非慣用方法并正確處理我想出的空值是:
// NullGoStruct returns false if value is nil or true otherwise
func NullGoStruct(value *GoStruct) bool {
return (value == nil)
}
然后檢查Java中的代碼,如:
GoLibrary.GoStruct value = GoLibrary.ExportedGoFunction();
if (GoLibrary.NullGoStruct(value)) {
// This block is executed only if value has nil value in Go
Log.d("GoLog", "value is null");
}

TA貢獻1891條經驗 獲得超3個贊
查看 go mobile 的測試包,看起來您需要將空值轉換為類型。
從 SeqTest.java 文件:
public void testNilErr() throws Exception {
Testpkg.Err(null); // returns nil, no exception
}
編輯:也是一個非例外示例:
byte[] got = Testpkg.BytesAppend(null, null);
assertEquals("Bytes(null+null) should match", (byte[])null, got);
got = Testpkg.BytesAppend(new byte[0], new byte[0]);
assertEquals("Bytes(empty+empty) should match", (byte[])null, got);
它可能很簡單:
GoLibrary.GoStruct goStruct = GoLibrary.ExportedGoFunction();
if (goStruct != (GoLibrary.GoStruct)null) {
// This block should not be executed, but it is
Log.d("GoLog", "goStruct is not null");
}
編輯:實用方法的建議:
您可以向庫中添加一個實用程序函數(shù)來為您提供鍵入的nil值。
func NullVal() *GoStruct {
return nil
}
仍然有點hacky,但它應該比多個包裝器和異常處理更少的開銷。
- 2 回答
- 0 關注
- 209 瀏覽
添加回答
舉報