回调如何工作
简介
在使用 Java API 时,有多种情况需要实现回调。实际的例子包括通过ContentObserver 来监听内容变化的回调,以及实现 Java 接口(如Handler.Callback )的回调。
QtJenny 允许在实现 Java 接口和扩展 Java 类的情况下实现此类回调,具体取决于 Java API 使用什么。Android 提供的许多跨平台 Java API 也使用接口回调,但 Android 也会在某些情况下使用抽象基类,一个突出的例子就是ContentObserver 。
实现 Java 接口
下图说明了在 C++ 中实现 Java 接口的结构和不同部分之间的逻辑划分。
其工作原理是,我们使用java.reflect.Proxy 封装 Java 接口,并将接口方法的调用分派给InvocationHandler 的通用invoke() 方法。
InvocationHandler 接口由特定于项目的NativeInvocationHandler (由您的应用程序提供)实现,该实现调用同样由项目提供的本地通用调用方法。本地方法调用生成的 C++ 类中的通用qt_invoke() 虚拟函数,该函数模仿 Java 接口。
最后,Qt C++ 项目中的用户代码继承生成的类,并覆盖其中的虚拟函数。
扩展 Java 类
下图说明了在 C++ 中扩展 Java 类的结构和不同部分之间的逻辑划分。
其工作原理是,我们生成一个 Java 子类,然后调用一个 Java 类的通用invoke() 方法。NativeInvocationHandler], which is a project-supplied Java class. The \c {NativeInvocationHandler} calls a native generic invocation method that is also project-supplied. The native method calls a generic \c {qt_invoke()} virtual function in a generated C++ class that mimics the Java class. Finally, the user code in the Qt C++ project inherits that generated class, and overrides the virtual functions in it.
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.