A convenience wrapper around the Java Native Interface (JNI). More...
Header: | #include <QJniObject> |
CMake: | find_package(Qt6 REQUIRED COMPONENTS Core) target_link_libraries(mytarget PRIVATE Qt6::Core) |
qmake: | QT += core |
Since: | Qt 6.1 |
QJniObject(jobject object) | |
QJniObject(jclass clazz, Args &&... args) | |
QJniObject(jclass clazz, const char *signature, ...) | |
QJniObject(jclass clazz) | |
QJniObject(const char *className, Args &&... args) | |
QJniObject(const char *className, const char *signature, ...) | |
QJniObject(const char *className) | |
QJniObject() | |
~QJniObject() | |
auto | callMethod(const char *methodName, const char *signature, Args &&... args) const |
auto | callMethod(const char *methodName, Args &&... args) const |
QJniObject | callObjectMethod(const char *methodName, Args &&... args) const |
QJniObject | callObjectMethod(const char *methodName, const char *signature, ...) const |
QByteArray | className() const |
auto | getField(const char *fieldName) const |
QJniObject | getObjectField(const char *fieldName) const |
QJniObject | getObjectField(const char *fieldName, const char *signature) const |
bool | isValid() const |
jobject | object() const |
jclass | objectClass() const |
void | setField(const char *fieldName, T value) |
void | setField(const char *fieldName, const char *signature, T value) |
QString | toString() const |
QJniObject & | operator=(T object) |
auto | callStaticMethod(const char *className, const char *methodName, const char *signature, Args &&... args) |
auto | callStaticMethod(jclass clazz, const char *methodName, const char *signature, Args &&... args) |
auto | callStaticMethod(jclass clazz, jmethodID methodId, Args &&... args) |
auto | callStaticMethod(const char *className, const char *methodName, Args &&... args) |
auto | callStaticMethod(jclass clazz, const char *methodName, Args &&... args) |
QJniObject | callStaticObjectMethod(const char *className, const char *methodName, const char *signature, ...) |
QJniObject | callStaticObjectMethod(jclass clazz, const char *methodName, const char *signature, ...) |
QJniObject | callStaticObjectMethod(jclass clazz, jmethodID methodId, ...) |
QJniObject | callStaticObjectMethod(const char *className, const char *methodName, Args &&... args) |
QJniObject | callStaticObjectMethod(jclass clazz, const char *methodName, Args &&... args) |
QJniObject | construct(Args &&... args) |
QJniObject | fromLocalRef(jobject localRef) |
QJniObject | fromString(const QString &string) |
auto | getStaticField(const char *className, const char *fieldName) |
auto | getStaticField(jclass clazz, const char *fieldName) |
auto | getStaticField(const char *fieldName) |
QJniObject | getStaticObjectField(const char *className, const char *fieldName) |
QJniObject | getStaticObjectField(const char *className, const char *fieldName, const char *signature) |
QJniObject | getStaticObjectField(jclass clazz, const char *fieldName) |
QJniObject | getStaticObjectField(jclass clazz, const char *fieldName, const char *signature) |
bool | isClassAvailable(const char *className) |
void | setStaticField(const char *className, const char *fieldName, T value) |
void | setStaticField(const char *className, const char *fieldName, const char *signature, T value) |
void | setStaticField(jclass clazz, const char *fieldName, const char *signature, T value) |
void | setStaticField(jclass clazz, const char *fieldName, T value) |
void | setStaticField(const char *fieldName, T value) |
bool | operator!=(const QJniObject &o1, const QJniObject &o2) |
bool | operator==(const QJniObject &o1, const QJniObject &o2) |
The QJniObject class wraps a reference to a Java object, ensuring it isn't gargage-collected and providing access to most JNIEnv
method calls (member, static) and fields (setter, getter). It eliminates much
boiler-plate that would normally be needed, with direct JNI access, for every operation, including exception-handling.
Note: This API has been designed and tested for use with Android. It has not been tested for other platforms.
"java/lang/String"
."(ArgumentsTypes)ReturnType"
, see JNI Types.
QJniObject provides convenience functions that will use the correct signature based on the provided template types. For functions that only return and take JNI types, the signature can be generate at compile time:
jint x = QJniObject::callMethod<jint>("getSize"); QJniObject::callMethod<void>("touch"); jint ret = jString1.callMethod<jint>("compareToIgnoreCase", jString2.object<jstring>());
These functions are variadic templates, and the compiler will deduce the template arguments from the actual argument types. In many situations, only the return type needs to be provided explicitly.
For functions that take other argument types, you need to supply the signature yourself. It is important that the signature matches the function you want to call. The example below demonstrates how to call different static functions:
// Java class package org.qtproject.qt; class TestClass { static TestClass create() { ... } static String fromNumber(int x) { ... } static String[] stringArray(String s1, String s2) { ... } }
The signature structure is "(ArgumentsTypes)ReturnType"
. Array types in the signature must have the [
prefix, and the fully-qualified Object
type names must have the L
prefix and the ;
suffix. The signature for the create
function is "()Lorg/qtproject/qt/TestClass;
. The signatures for the second and third functions are
"(I)Ljava/lang/String;"
and "(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;"
, respectively.
We can call the create()
function like this:
// C++ code QJniObject testClass = QJniObject::callStaticObjectMethod("org/qtproject/qt/TestClass", "create", "()Lorg/qtproject/qt/TestClass;");
For the second and third function we can rely on QJniObject's template methods to create the implicit signature string, but we can also pass the signature string explicitly:
// C++ code QJniObject stringNumber = QJniObject::callStaticObjectMethod("org/qtproject/qt/TestClass", "fromNumber", "(I)Ljava/lang/String;", 10);
For the implicit signature creation to work we need to specify the return type explicitly:
// C++ code QJniObject string1 = QJniObject::fromString("String1"); QJniObject string2 = QJniObject::fromString("String2"); QJniObject stringArray = QJniObject::callStaticObjectMethod<jstringArray>( "org/qtproject/qt/TestClass", "stringArray" string1.object<jstring>(), string2.object<jstring>());
Note that while he first template parameter specifies the return type of the Java function, the method will still return a QJniObject.
After calling Java functions that might throw exceptions, it is important to check for, handle and clear out any exception before continuing. All QJniObject functions handle exceptions internally by reporting and clearing them, saving client code the need to handle exceptions.
Note: The user must handle exceptions manually when doing JNI calls using JNIEnv
directly. It is unsafe to make other JNI calls when exceptions are pending. For more information, see QJniEnvironment::checkAndClearExceptions().
Java native methods makes it possible to call native code from Java, this is done by creating a function declaration in Java and prefixing it with the native
keyword. Before a native function can be called from
Java, you need to map the Java native function to a native function in your code. Mapping functions can be done by calling QJniEnvironment::registerNativeMethods().
The example below demonstrates how this could be done.
Java implementation:
class FooJavaClass { public static void foo(int x) { if (x < 100) callNativeOne(x); else callNativeTwo(x); } private static native void callNativeOne(int x); private static native void callNativeTwo(int x); }
C++ Implementation:
static void fromJavaOne(JNIEnv *env, jobject thiz, jint x) { Q_UNUSED(env); Q_UNUSED(thiz); qDebug() << x << "< 100"; } static void fromJavaTwo(JNIEnv *env, jobject thiz, jint x) { Q_UNUSED(env); Q_UNUSED(thiz); qDebug() << x << ">= 100"; } void foo() { // register the native methods first, ideally it better be done with the app start const JNINativeMethod methods[] = {{"callNativeOne", "(I)V", reinterpret_cast<void *>(fromJavaOne)}, {"callNativeTwo", "(I)V", reinterpret_cast<void *>(fromJavaTwo)}}; QJniEnvironment env; env.registerNativeMethods("my/java/project/FooJavaClass", methods, 2); // Call the java method which will calls back to the C++ functions QJniObject::callStaticMethod<void>("my/java/project/FooJavaClass", "foo", "(I)V", 10); // Output: 10 < 100 QJniObject::callStaticMethod<void>("my/java/project/FooJavaClass", "foo", "(I)V", 100); // Output: 100 >= 100 }
Most objects received from Java will be local references and will only stay valid until you return from the native method. After that, the object becomes eligible for garbage collection. If your code creates many local references in a loop you should delete them manually with each iteration, otherwise you might run out of memory. For more information, see JNI Design Overview: Global and Local References. Local references created outside a native method scope must be deleted manually, since the garbage collector will not free them automatically because we are using AttachCurrentThread. For more information, see JNI tips: Local and global references.
If you want to keep a Java object alive you need to either create a new global reference to the object and release it when you are done, or construct a new QJniObject and let it manage the lifetime of the Java object.
Note: The QJniObject only manages its own references, if you construct a QJniObject from a global or local reference that reference will not be released by the QJniObject.
Type | Signature |
---|---|
jobject | Ljava/lang/Object; |
jclass | Ljava/lang/Class; |
jstring | Ljava/lang/String; |
jthrowable | Ljava/lang/Throwable; |
jobjectArray | [Ljava/lang/Object; |
jarray | [<type> |
jbooleanArray | [Z |
jbyteArray | [B |
jcharArray | [C |
jshortArray | [S |
jintArray | [I |
jlongArray | [J |
jfloatArray | [F |
jdoubleArray | [D |
Type | Signature |
---|---|
jboolean | Z |
jbyte | B |
jchar | C |
jshort | S |
jint | I |
jlong | J |
jfloat | F |
jdouble | D |
Type | Signature |
---|---|
void | V |
Custom type | L<fully-qualified-name>; |
For more information about JNI, see Java Native Interface Specification.
See also QJniEnvironment and object().
Constructs a new JNI object around the Java object object.
Note: The QJniObject will hold a reference to the Java object object and release it when destroyed. Any references to the Java object object outside QJniObject needs to be managed by the caller. In most cases you should never call this function with a local reference unless you intend to manage the local reference yourself. See QJniObject::fromLocalRef() for converting a local reference to a QJniObject.
See also fromLocalRef().
[since 6.4]
template <typename Args> QJniObject::QJniObject(jclass clazz, Args
&&... args)Constructs a new JNI object from clazz by calling the constructor with the arguments args. This constructor is only available if all args are known JNI Types.
QJniEnvironment env; jclass myClazz = env.findClass("org/qtproject/qt/TestClass"); QJniObject(myClazz, 3);
This function was introduced in Qt 6.4.
Constructs a new JNI object from clazz by calling the constructor with signature specifying the types of any subsequent arguments.
QJniEnvironment env; jclass myClazz = env.findClass("org/qtproject/qt/TestClass"); QJniObject(myClazz, "(I)V", 3);
Constructs a new JNI object by calling the default constructor of clazz.
Note: The QJniObject will create a new reference to the class clazz and releases it again when it is destroyed. References to the class created outside the QJniObject need to be managed by the caller.
[since 6.4]
template <typename Args> QJniObject::QJniObject(const char *className, Args
&&... args)Constructs a new JNI object by calling the constructor of className with the arguments args. This constructor is only available if all args are known JNI Types.
QJniEnvironment env; char* str = "Hello"; jstring myJStringArg = env->NewStringUTF(str); QJniObject myNewJavaString("java/lang/String", myJStringArg);
This function was introduced in Qt 6.4.
Constructs a new JNI object by calling the constructor of className with signature specifying the types of any subsequent arguments.
QJniEnvironment env; char* str = "Hello"; jstring myJStringArg = env->NewStringUTF(str); QJniObject myNewJavaString("java/lang/String", "(Ljava/lang/String;)V", myJStringArg);
Constructs a new JNI object by calling the default constructor of className.
QJniObject myJavaString("java/lang/String");
Constructs an invalid JNI object.
See also isValid().
Destroys the JNI object and releases any references held by the JNI object.
[since 6.4]
template <typename Ret, typename Args> auto QJniObject::callMethod(const char
*methodName, const char *signature, Args &&... args) constCalls the object's method methodName with signature specifying the types of any subsequent arguments args, and returns the value (unless Ret
is void
). If Ret
is a
jobject type, then the returned value will be a QJniObject.
QJniObject myJavaStrin("org/qtproject/qt/TestClass"); jint index = myJavaString.callMethod<jint>("indexOf", "(I)I", 0x0051);
This function was introduced in Qt 6.4.
[since 6.4]
template <typename Ret, typename Args> auto QJniObject::callMethod(const char
*methodName, Args &&... args) constCalls the method methodName with arguments args and returns the value (unless Ret
is void
). If Ret
is a jobject type, then the returned value will be a QJniObject.
QJniObject myJavaStrin("org/qtproject/qt/TestClass"); jint size = myJavaString.callMethod<jint>("length");
The method signature is deduced at compile time from Ret
and the types of args.
This function was introduced in Qt 6.4.
[since 6.4]
template <typename Ret, typename Args> QJniObject QJniObject::callObjectMethod(const char *methodName, Args &&... args) constCalls the Java objects method methodName with arguments args and returns a new QJniObject for the returned Java object.
QJniObject myJavaString = QJniObject::fromString("Hello, Java"); QJniObject myJavaString2 = myJavaString1.callObjectMethod<jstring>("toString");
The method signature is deduced at compile time from Ret
and the types of args.
This function was introduced in Qt 6.4.
Calls the Java object's method methodName with signature specifying the types of any subsequent arguments.
QJniObject myJavaString = QJniObject::fromString("Hello, Java"); QJniObject mySubstring = myJavaString.callObjectMethod("substring", "(II)Ljava/lang/String;", 7, 11);
[static, since 6.4]
template <typename Ret, typename Args> auto QJniObject::callStaticMethod(const char *className, const char *methodName, const char *signature, Args &&... args)Calls the static method methodName from class className with signature specifying the types of any subsequent arguments args. Returns the result of the method (unless Ret
is
void
). If Ret
is a jobject type, then the returned value will be a QJniObject.
jint a = 2; jint b = 4; jint max = QJniObject::callStaticMethod<jint>("java/lang/Math", "max", "(II)I", a, b);
This function was introduced in Qt 6.4.
[static]
template <typename Ret, typename Args> auto QJniObject::callStaticMethod(jclass
clazz, const char *methodName, const char *signature, Args &&... args)Calls the static method methodName from clazz with signature specifying the types of any subsequent arguments. Returns the result of the method (unless Ret
is void
). If
Ret
is a jobject type, then the returned value will be a QJniObject.
QJniEnvironment env; jclass javaMathClass = env.findClass("java/lang/Math"); jint a = 2; jint b = 4; jint max = QJniObject::callStaticMethod<jint>(javaMathClass, "max", "(II)I", a, b);
[static, since 6.4]
template <typename Ret, typename Args> auto QJniObject::callStaticMethod(jclass clazz, jmethodID methodId, Args &&... args)Calls the static method identified by methodId from the class clazz with any subsequent arguments, and returns the value of type Ret
(unless Ret
is void
). If
Ret
is a jobject type, then the returned value will be a QJniObject.
Useful when clazz and methodId are already cached from previous operations.
QJniEnvironment env; jclass javaMathClass = env.findClass("java/lang/Math"); jmethodID methodId = env.findStaticMethod(javaMathClass, "max", "(II)I"); if (methodId != 0) { jint a = 2; jint b = 4; jint max = QJniObject::callStaticMethod<jint>(javaMathClass, methodId, a, b); }
This function was introduced in Qt 6.4.
[static, since 6.4]
template <typename Ret, typename Args> auto QJniObject::callStaticMethod(const char *className, const char *methodName, Args &&... args)Calls the static method methodName on class className with arguments args, and returns the value of type Ret
(unless Ret
is void
). If Ret
is a jobject
type, then the returned value will be a QJniObject.
jint value = QJniObject::callStaticMethod<jint>("MyClass", "staticMethod");
The method signature is deduced at compile time from Ret
and the types of args.
This function was introduced in Qt 6.4.
[static, since 6.4]
template <typename Ret, typename Args> auto QJniObject::callStaticMethod(jclass clazz, const char *methodName, Args &&... args)Calls the static method methodName on clazz and returns the value of type Ret
(unless c Ret is void
). If Ret
if a jobject type, then the returned value will be a QJniObject.
QJniEnvironment env; jclass javaMathClass = env.findClass("java/lang/Math"); jdouble randNr = QJniObject::callStaticMethod<jdouble>(javaMathClass, "random");
The method signature is deduced at compile time from Ret
and the types of args.
This function was introduced in Qt 6.4.
[static]
QJniObject QJniObject::callStaticObjectMethod(const char *className, const char *methodName, const char *signature, ...)Calls the static method methodName from the class className with signature specifying the types of any subsequent arguments.
QJniObject thread = QJniObject::callStaticObjectMethod("java/lang/Thread", "currentThread", "()Ljava/lang/Thread;"); QJniObject string = QJniObject::callStaticObjectMethod("java/lang/String", "valueOf", "(I)Ljava/lang/String;", 10);
[static]
QJniObject QJniObject::callStaticObjectMethod(jclass clazz, const char *methodName, const char *signature, ...)Calls the static method methodName from class clazz with signature specifying the types of any subsequent arguments.
[static]
QJniObject QJniObject::callStaticObjectMethod(jclass clazz, jmethodID methodId, ...)Calls the static method identified by methodId from the class clazz with any subsequent arguments. Useful when clazz and methodId are already cached from previous operations.
QJniEnvironment env; jclass clazz = env.findClass("java/lang/String"); jmethodID methodId = env.findStaticMethod(clazz, "valueOf", "(I)Ljava/lang/String;"); if (methodId != 0) QJniObject str = QJniObject::callStaticObjectMethod(clazz, methodId, 10);
[static, since 6.4]
template <typename Ret, typename Args> QJniObject
QJniObject::callStaticObjectMethod(const char *className, const char *methodName, Args &&...
args)Calls the static method with methodName on the class className, passing arguments args, and returns a new QJniObject for the returned Java object.
QJniObject string = QJniObject::callStaticObjectMethod<jstring>("CustomClass", "getClassName");
The method signature is deduced at compile time from Ret
and the types of args.
This function was introduced in Qt 6.4.
[static, since 6.4]
template <typename Ret, typename Args> QJniObject
QJniObject::callStaticObjectMethod(jclass clazz, const char *methodName, Args &&... args)Calls the static method with methodName on clazz, passing arguments args, and returns a new QJniObject for the returned Java object.
This function was introduced in Qt 6.4.
[since 6.2]
QByteArray QJniObject::className() constReturns the name of the class object held by the QJniObject as a QByteArray
.
This function was introduced in Qt 6.2.
[static, since 6.4]
template <typename Class, typename Args> QJniObject QJniObject::construct(Args &&... args)Constructs an instance of the Java class that is the equivalent of Class
and returns a QJniObject containing the JNI object. The arguments in args are passed to the Java
constructor.
QJniObject javaString = QJniObject::construct<jstring>();
This function is only available if all args are known JNI Types.
This function was introduced in Qt 6.4.
[static]
QJniObject QJniObject::fromLocalRef(jobject
localRef)Creates a QJniObject from the local JNI reference localRef. This function takes ownership of localRef and frees it before returning.
Note: Only call this function with a local JNI reference. For example, most raw JNI calls, through the JNI environment, return local references to a java object.
jobject localRef = env->GetObjectArrayElement(array, index); QJniObject element = QJniObject::fromLocalRef(localRef);
[static]
QJniObject QJniObject::fromString(const QString &string)Creates a Java string from the QString string and returns a QJniObject holding that string.
QString myQString = "QString"; QJniObject myJavaString = QJniObject::fromString(myQString);
See also toString().
Retrieves the value of the field fieldName.
QJniObject volumeControl("org/qtproject/qt/TestClass"); jint fieldValue = volumeControl.getField<jint>("FIELD_NAME");
Retrieves a JNI object from the field fieldName.
QJniObject field = jniObject.getObjectField<jstring>("FIELD_NAME");
Retrieves a JNI object from the field fieldName with signature.
Note: This function can be used without a template type.
QJniObject field = jniObject.getObjectField("FIELD_NAME", "Ljava/lang/String;");
[static]
template <typename T> auto QJniObject::getStaticField(const char *className,
const char *fieldName)Retrieves the value from the static field fieldName on the class className.
[static]
template <typename T> auto QJniObject::getStaticField(jclass clazz, const
char *fieldName)Retrieves the value from the static field fieldName on clazz.
[static]
template <typename Klass, typename T> auto QJniObject::getStaticField(const char
*fieldName)Retrieves the value from the static field fieldName for the class Klass
.
Klass
needs to be a C++ type with a registered type mapping to a Java type.
[static]
template <typename T> QJniObject QJniObject::getStaticObjectField(const char *className, const char *fieldName)Retrieves the object from the field fieldName on the class className.
QJniObject jobj = QJniObject::getStaticObjectField<jstring>("class/with/Fields", "FIELD_NAME");
[static]
QJniObject QJniObject::getStaticObjectField(const char *className, const char *fieldName, const char *signature)Retrieves a JNI object from the field fieldName with signature from class className.
Note: This function can be used without a template type.
QJniObject jobj = QJniObject::getStaticObjectField("class/with/Fields", "FIELD_NAME", "Ljava/lang/String;");
[static]
template <typename T> QJniObject QJniObject::getStaticObjectField(jclass clazz, const char *fieldName)Retrieves the object from the field fieldName on clazz.
QJniObject jobj = QJniObject::getStaticObjectField<jstring>(clazz, "FIELD_NAME");
[static]
QJniObject QJniObject::getStaticObjectField(jclass clazz, const char *fieldName, const char *signature)Retrieves a JNI object from the field fieldName with signature from class clazz.
Note: This function can be used without a template type.
QJniObject jobj = QJniObject::getStaticObjectField(clazz, "FIELD_NAME", "Ljava/lang/String;");
[static]
bool QJniObject::isClassAvailable(const char *className)Returns true if the Java class className is available.
if (QJniObject::isClassAvailable("java/lang/String")) { // condition statement }
Returns true if this instance holds a valid Java object.
QJniObject qjniObject; // ==> isValid() == false QJniObject qjniObject(0) // ==> isValid() == false QJniObject qjniObject("could/not/find/Class") // ==> isValid() == false
Returns the object held by the QJniObject either as jobject or as type T. T can be one of JNI Object Types.
QJniObject string = QJniObject::fromString("Hello, JNI"); jstring jstring = string.object<jstring>();
Note: The returned object is still kept alive by this QJniObject. To keep the object alive beyond the lifetime of this QJniObject, for example to record it for later use, the easiest approach is to store it in another QJniObject with a suitable lifetime. Alternatively, you may create a new global reference to the object and store it, taking care to free it when you are done with it.
void functionScope() { QString helloString("Hello"); jstring myJString = 0; { QJniObject string = QJniObject::fromString(helloString); myJString = string.object<jstring>(); } // Ops! myJString is no longer valid. }
[since 6.2]
jclass QJniObject::objectClass() constReturns the class object held by the QJniObject as a jclass
.
Note: The returned object is still kept alive by this QJniObject. To keep the object alive beyond the lifetime of this QJniObject, for example to record it for later use, the easiest approach is to store it in another QJniObject with a suitable lifetime. Alternatively, you may create a new global reference to the object and store it, taking care to free it when you are done with it.
This function was introduced in Qt 6.2.
Sets the value of fieldName to value.
QJniObject obj; obj.setField<jint>("AN_INT_FIELD", 10); jstring myString = ...; obj.setField<jstring>("A_STRING_FIELD", myString);
Sets the value of fieldName with signature to value.
QJniObject stringArray = ...; QJniObject obj = ...; obj.setObjectField<jobjectArray>("KEY_VALUES", "([Ljava/lang/String;)V", stringArray.object<jobjectArray>())
[static]
template <typename T> void QJniObject::setStaticField(const char *className,
const char *fieldName, T value)Sets the static field fieldName of the class className to value.
[static]
template <typename T> void QJniObject::setStaticField(const char *className,
const char *fieldName, const char *signature, T value)Sets the static field fieldName on the class className to value using the setter with signature.
[static]
template <typename T> void QJniObject::setStaticField(jclass clazz, const
char *fieldName, const char *signature, T value)Sets the static field fieldName on the class clazz to value using the setter with signature.
[static]
template <typename T> void QJniObject::setStaticField(jclass clazz, const
char *fieldName, T value)Sets the static field fieldName of the class clazz to value.
[static]
template <typename Klass, typename T> void QJniObject::setStaticField(const char
*fieldName, T value)Sets the static field fieldName of the class Klass
to value.
Klass
needs to be a C++ type with a registered type mapping to a Java type.
Returns a QString with a string representation of the java object. Calling this function on a Java String object is a convenient way of getting the actual string data.
QJniObject string = ...; // "Hello Java" QString qstring = string.toString(); // "Hello Java"
See also fromString().
Replace the current object with object. The old Java object will be released.
Returns true if o1 holds a reference to a different object than o2.
Returns true if both objects, o1 and o2, are referencing the same Java object, or if both are NULL. In any other cases false will be returned.