Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

JavaClassWrapper

繼承: Object

提供對 Java 原生介面的存取。

說明

JavaClassWrapper 單例為 Godot 應用程式提供了一種通過 Java 原生介面(JNI)發送和接收資料的方法。

注意:該單例僅適用於 Android 版本。

var LocalDateTime = JavaClassWrapper.wrap("java.time.LocalDateTime")
var DateTimeFormatter = JavaClassWrapper.wrap("java.time.format.DateTimeFormatter")

var datetime = LocalDateTime.now()
var formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss")

print(datetime.format(formatter))

警告:呼叫 Java 方法時,請確保使用 get_exception() 檢查該方法是否拋出了異常。

教學

方法

JavaObject

create_proxy(object: Object, interfaces: PackedStringArray)

JavaObject

create_sam_callback(sam_interface: String, callable: Callable)

JavaObject

get_exception()

JavaClass

wrap(name: String)


方法說明

JavaObject create_proxy(object: Object, interfaces: PackedStringArray) 🔗

建立一個實作指定 Java 介面的 JavaObject,並使用給定的 Object 作為具體實作。

object 必須包含與傳入的 Java interfaces 中方法簽名相匹配的方法簽名。呼叫 Java interfaces 中的方法時,將路由至對應的 object 方法。

class PrintProxy:
    func println(content: String) -> void:
        print(content)

var print_proxy = PrintProxy.new()
var printer_object = JavaClassWrapper.create_proxy(print_proxy, ["android.util.Printer"])
printer_object.println("Hello Godot World!")

注意: 該方法僅適用於 Android 平台。在其他所有平台上,該方法始終回傳 null。


JavaObject create_sam_callback(sam_interface: String, callable: Callable) 🔗

建立一個實作 Java 單一抽象方法(SAM)介面的 JavaObject,並使用 Godot 的 Callable 作為具體實作。

sam_interface 必須是一個 Java SAM 介面,這意味著它必須僅包含一個需要實作的抽象方法。

callable 必須能夠處理與 SAM 介面方法相同的參數型別,並提供相同的回傳型別。該 callable 將作為回呼被呼叫,並傳入來自 Java SAM 介面方法的參數。

var cb = func (content: String) -> void:
    print(content)
var callback = JavaClassWrapper.create_sam_callback("android.util.Printer", cb)
callback.println("Hello Godot World!")

注意: 該方法僅適用於 Android 平台。在其他所有平台上,該方法始終回傳 null。


JavaObject get_exception() 🔗

回傳最近一次呼叫 Java 類時產生的 Java 異常。如果沒有產生異常則回傳 null。

注意:該方法僅在 Android 上有效。該方法在其他平台上始終回傳 null。


JavaClass wrap(name: String) 🔗

包裝 Java 中定義的類,回傳 Godot 可以與之互動的 Object 型別 JavaClass。

包裝內部(巢狀)類時請使用 $ 分隔,不要用 .。例如 WindowManager.LayoutParams 類應使用 JavaClassWrapper.wrap("android.view.WindowManager$LayoutParams") 進行包裝。

注意:呼叫建構函式請呼叫與類同名的方法。例如:

var Intent = JavaClassWrapper.wrap("android.content.Intent")
var intent = Intent.Intent()

注意:該方法僅適用於 Android,在其他所有平台上都不會執行任何操作,回傳的是空的 JavaClass。