QJniObject Class

A convenience wrapper around the Java Native Interface (JNI). More...

Header: #include <QJniObject>
CMake: find_package(Qt6 COMPONENTS Core REQUIRED)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core
Since: Qt 6.1

Public Functions

QJniObject(jobject object)
QJniObject(jclass clazz, const char *signature, ...)
QJniObject(jclass clazz)
QJniObject(const char *className, const char *signature, ...)
QJniObject(const char *className)
QJniObject()
~QJniObject()
T callMethod(const char *methodName, const char *signature, ...) const
T callMethod(const char *methodName) const
QJniObject callObjectMethod(const char *methodName) const
QJniObject callObjectMethod(const char *methodName, const char *signature, ...) const
QByteArray className() const
T 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)

Static Public Members

T callStaticMethod(const char *className, const char *methodName, const char *signature, ...)
T callStaticMethod(const char *className, const char *methodName)
T callStaticMethod(jclass clazz, const char *methodName, const char *signature, ...)
T callStaticMethod(jclass clazz, jmethodID methodId, ...)
T callStaticMethod(jclass clazz, const char *methodName)
QJniObject callStaticObjectMethod(const char *className, const char *methodName)
QJniObject callStaticObjectMethod(const char *className, const char *methodName, const char *signature, ...)
QJniObject callStaticObjectMethod(jclass clazz, const char *methodName)
QJniObject callStaticObjectMethod(jclass clazz, const char *methodName, const char *signature, ...)
QJniObject callStaticObjectMethod(jclass clazz, jmethodID methodId, ...)
QJniObject fromLocalRef(jobject localRef)
QJniObject fromString(const QString &string)
T getStaticField(const char *className, const char *fieldName)
T getStaticField(jclass clazz, 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)
bool operator!=(const QJniObject &o1, const QJniObject &o2)
bool operator==(const QJniObject &o1, const QJniObject &o2)

Detailed Description

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.

General Notes

  • Class names need to be fully-qualified, for example: "java/lang/String".
  • Method signatures are written as "(ArgumentsTypes)ReturnType", see JNI Types.
  • All object types are returned as a QJniObject.

Method Signatures

For functions that take no arguments, QJniObject provides convenience functions that will use the correct signature based on the provided template type. For example:

jint x = QJniObject::callMethod<jint>("getSize");
QJniObject::callMethod<void>("touch");

In other cases you will need to supply the signature yourself, and it is important that the signature matches the function you want to call. 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 example below demonstrates how to call two different static functions:

// Java class
package org.qtproject.qt;
class TestClass
{
   static String fromNumber(int x) { ... }
   static String[] stringArray(String s1, String s2) { ... }
}

The signature for the first function is "(I)Ljava/lang/String;":

// C++ code
QJniObject stringNumber = QJniObject::callStaticObjectMethod("org/qtproject/qt/TestClass",
                                                             "fromNumber"
                                                             "(I)Ljava/lang/String;",
                                                             10);

and the signature for the second function is "(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;":

// C++ code
QJniObject string1 = QJniObject::fromString("String1");
QJniObject string2 = QJniObject::fromString("String2");
QJniObject stringArray = QJniObject::callStaticObjectMethod("org/qtproject/qt/TestClass",
                                                            "stringArray"
                                                            "(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;"
                                                            string1.object<jstring>(),
                                                            string2.object<jstring>());

Handling Java Exception

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

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
}

The Lifetime of a Java Object

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.

JNI Types

Object Types

TypeSignature
jobjectLjava/lang/Object;
jclassLjava/lang/Class;
jstringLjava/lang/String;
jthrowableLjava/lang/Throwable;
jobjectArray[Ljava/lang/Object;
jarray[<type>
jbooleanArray[Z
jbyteArray[B
jcharArray[C
jshortArray[S
jintArray[I
jlongArray[J
jfloatArray[F
jdoubleArray[D

Primitive Types

TypeSignature
jbooleanZ
jbyteB
jcharC
jshortS
jintI
jlongJ
jfloatF
jdoubleD

Other

TypeSignature
voidV
Custom typeL<fully-qualified-name>;

For more information about JNI, see Java Native Interface Specification.

See also QJniEnvironment and object().

Member Function Documentation

QJniObject::QJniObject(jobject 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().

QJniObject::QJniObject(jclass clazz, const char *signature, ...)

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);

QJniObject::QJniObject(jclass clazz)

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.

QJniObject::QJniObject(const char *className, const char *signature, ...)

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);

QJniObject::QJniObject(const char *className)

Constructs a new JNI object by calling the default constructor of className.

QJniObject myJavaString("java/lang/String");

QJniObject::QJniObject()

Constructs an invalid JNI object.

See also isValid().

QJniObject::~QJniObject()

Destroys the JNI object and releases any references held by the JNI object.

template <typename T> T QJniObject::callMethod(const char *methodName, const char *signature, ...) const

Calls the object's method methodName with signature specifying the types of any subsequent arguments.

QJniObject myJavaStrin("org/qtproject/qt/TestClass");
jint index = myJavaString.callMethod<jint>("indexOf", "(I)I", 0x0051);

template <typename T> T QJniObject::callMethod(const char *methodName) const

Calls the method methodName and returns the value.

QJniObject myJavaStrin("org/qtproject/qt/TestClass");
jint size = myJavaString.callMethod<jint>("length");

template <typename T> QJniObject QJniObject::callObjectMethod(const char *methodName) const

Calls the Java objects method methodName and returns a new QJniObject for the returned Java object.

QJniObject myJavaString = QJniObject::fromString("Hello, Java");
QJniObject myJavaString2 = myJavaString1.callObjectMethod<jstring>("toString");

QJniObject QJniObject::callObjectMethod(const char *methodName, const char *signature, ...) const

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] template <typename T> T QJniObject::callStaticMethod(const char *className, const char *methodName, const char *signature, ...)

Calls the static method methodName from class className with signature specifying the types of any subsequent arguments.

jint a = 2;
jint b = 4;
jint max = QJniObject::callStaticMethod<jint>("java/lang/Math", "max", "(II)I", a, b);

[static] template <typename T> T QJniObject::callStaticMethod(const char *className, const char *methodName)

Calls the static method methodName on class className and returns the value.

jint value = QJniObject::callStaticMethod<jint>("MyClass", "staticMethod");

[static] template <typename T> T QJniObject::callStaticMethod(jclass clazz, const char *methodName, const char *signature, ...)

Calls the static method methodName from clazz with signature specifying the types of any subsequent arguments.

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] template <typename T> T QJniObject::callStaticMethod(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 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);
}

[static] template <typename T> T QJniObject::callStaticMethod(jclass clazz, const char *methodName)

Calls the static method methodName on clazz and returns the value.

QJniEnvironment env;
jclass javaMathClass = env.findClass("java/lang/Math");
jdouble randNr = QJniObject::callStaticMethod<jdouble>(javaMathClass, "random");

[static] template <typename T> QJniObject QJniObject::callStaticObjectMethod(const char *className, const char *methodName)

Calls the static method with methodName on the class className.

QJniObject string = QJniObject::callStaticObjectMethod<jstring>("CustomClass", "getClassName");

[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] template <typename T> QJniObject QJniObject::callStaticObjectMethod(jclass clazz, const char *methodName)

Calls the static method with methodName on clazz.

[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);

[since 6.2] QByteArray QJniObject::className() const

Returns the name of the class object held by the QJniObject as a QByteArray.

This function was introduced in Qt 6.2.

[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().

template <typename T> T QJniObject::getField(const char *fieldName) const

Retrieves the value of the field fieldName.

QJniObject volumeControl("org/qtproject/qt/TestClass");
jint fieldValue = volumeControl.getField<jint>("FIELD_NAME");

template <typename T> QJniObject QJniObject::getObjectField(const char *fieldName) const

Retrieves a JNI object from the field fieldName.

QJniObject field = jniObject.getObjectField<jstring>("FIELD_NAME");

QJniObject QJniObject::getObjectField(const char *fieldName, const char *signature) const

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> T QJniObject::getStaticField(const char *className, const char *fieldName)

Retrieves the value from the static field fieldName on the class className.

[static] template <typename T> T QJniObject::getStaticField(jclass clazz, const char *fieldName)

Retrieves the value from the static field fieldName on clazz.

[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
}

bool QJniObject::isValid() const

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

jobject QJniObject::object() const

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() const

Returns 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.

template <typename T> void QJniObject::setField(const char *fieldName, T value)

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);

template <typename T> void QJniObject::setField(const char *fieldName, const char *signature, T value)

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.

QString QJniObject::toString() const

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().

template <typename T> QJniObject &QJniObject::operator=(T object)

Replace the current object with object. The old Java object will be released.

Related Non-Members

bool operator!=(const QJniObject &o1, const QJniObject &o2)

Returns true if o1 holds a reference to a different object than o2.

bool operator==(const QJniObject &o1, const QJniObject &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.

© 2024 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.