- Qt 6.8
- Qt Core
- C++ Classes
- QJniEnvironment
- Qt 6.8.1 Reference Documentation

# QJniEnvironment Class

The QJniEnvironment class provides access to the JNI Environment (JNIEnv). More...

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

- List of all members, including inherited members
- Deprecated members

## Public Types

enum class | OutputMode { Silent, Verbose }

## Public Functions

| QJniEnvironment()
| ~QJniEnvironment()
bool | checkAndClearExceptions(QJniEnvironment::OutputMode outputMode = OutputMode::Verbose)
jclass | findClass(const char *className)
`(since 6.4)` jfieldID | findField(jclass clazz, const char *fieldName)
`(since 6.2)` jfieldID | findField(jclass clazz, const char *fieldName, const char *signature)
`(since 6.4)` jmethodID | findMethod(jclass clazz, const char *methodName)
`(since 6.2)` jmethodID | findMethod(jclass clazz, const char *methodName, const char *signature)
`(since 6.4)` jfieldID | findStaticField(jclass clazz, const char *fieldName)
`(since 6.2)` jfieldID | findStaticField(jclass clazz, const char *fieldName, const char *signature)
`(since 6.4)` jmethodID | findStaticMethod(jclass clazz, const char *methodName)
`(since 6.2)` jmethodID | findStaticMethod(jclass clazz, const char *methodName, const char *signature)
`(since 6.2)` bool | isValid() const
JNIEnv * | jniEnv() const
bool | registerNativeMethods(std::initializer_list<JNINativeMethod> methods)
bool | registerNativeMethods(const char *className, std::initializer_list<JNINativeMethod> methods)
bool | registerNativeMethods(jclass clazz, std::initializer_list<JNINativeMethod> methods)
bool | registerNativeMethods(const char *className, const JNINativeMethod[] methods, int size)
bool | registerNativeMethods(jclass clazz, const JNINativeMethod[] methods, int size)
JNIEnv & | operator*() const
JNIEnv * | operator->() const

## Static Public Members

bool | checkAndClearExceptions(JNIEnv *env, QJniEnvironment::OutputMode outputMode = OutputMode::Verbose)
JNIEnv * | getJniEnv()
JavaVM * | javaVM()

## Detailed Description

When using JNI, the JNIEnv class is a pointer to a function table and a member function for each JNI function that indirects through the table. `JNIEnv` provides most of the JNI functions. Every C++ native function receives a `JNIEnv` as the first argument. The JNI environment cannot be shared between threads.

Since `JNIEnv` doesn't do much error checking, such as exception checking and clearing, QJniEnvironment allows you to do that easily.

For more information about JNIEnv, see Java: Interface Function Table.

Note: This API has been designed and tested for use with Android. It has not been tested for other platforms.

## Member Type Documentation

### enum class QJniEnvironment::OutputMode

Constant | Value | Description
--- | --- | ---
`QJniEnvironment::OutputMode::Silent` | `0` | The exceptions are cleaned silently
`QJniEnvironment::OutputMode::Verbose` | `1` | Prints the exceptions and their stack backtrace as an error to `stderr` stream.

## Member Function Documentation

### QJniEnvironment::QJniEnvironment()

Constructs a new JNI Environment object and attaches the current thread to the Java VM.

### `[noexcept]` QJniEnvironment::~QJniEnvironment()

Detaches the current thread from the Java VM and destroys the QJniEnvironment object. This will clear any pending exception by calling checkAndClearExceptions().

### bool QJniEnvironment::checkAndClearExceptions(QJniEnvironment::OutputMode outputMode = OutputMode::Verbose)

Cleans any pending exceptions either silently or reporting stack backtrace, depending on the outputMode.

In contrast to QJniObject, which handles exceptions internally, if you make JNI calls directly via `JNIEnv`, you need to clear any potential exceptions after the call using this function. For more information about `JNIEnv` calls that can throw an exception, see JNI Functions.

Returns `true` when a pending exception was cleared.

### `[static]` bool QJniEnvironment::checkAndClearExceptions(JNIEnv *env, QJniEnvironment::OutputMode outputMode = OutputMode::Verbose)

Cleans any pending exceptions for env, either silently or reporting stack backtrace, depending on the outputMode. This is useful when you already have a `JNIEnv` pointer such as in a native function implementation.

In contrast to QJniObject, which handles exceptions internally, if you make JNI calls directly via `JNIEnv`, you need to clear any potential exceptions after the call using this function. For more information about `JNIEnv` calls that can throw an exception, see JNI Functions.

Returns `true` when a pending exception was cleared.

### jclass QJniEnvironment::findClass(const char *className)

Searches for className using all available class loaders. Qt on Android uses a custom class loader to load all the .jar files and it must be used to find any classes that are created by that class loader because these classes are not visible when using the default class loader.

Returns the class pointer or null if className is not found.

A use case for this function is searching for a class to call a JNI method that takes a `jclass`. This can be useful when doing multiple JNI calls on the same class object which can a bit faster than using a class name in each call. Additionally, this call looks for internally cached classes first before doing a JNI call, and returns such a class if found. The following code snippet creates an instance of the class `CustomClass` and then calls the `printFromJava()` method:

     QJniEnvironment env;
     jclass javaClass = env.findClass("org/qtproject/example/android/CustomClass");
     QJniObject javaMessage = QJniObject::fromString("findClass example");
     QJniObject::callStaticMethod<void>(javaClass, "printFromJava",
                                        "(Ljava/lang/String;)V", javaMessage.object<jstring>());

Note: This call returns a global reference to the class object from the internally cached classes.

### `[since 6.4]` template <typename T> jfieldID QJniEnvironment::findField(jclass clazz, const char *fieldName)

Searches for a member field of a class clazz. The field is specified by its fieldName. The signature of the field is deduced from the template parameter.

Returns the field ID or `nullptr` if the field is not found.

This function was introduced in Qt 6.4.

### `[since 6.2]` jfieldID QJniEnvironment::findField(jclass clazz, const char *fieldName, const char *signature)

Searches for a member field of a class clazz. The field is specified by its fieldName and signature.

Returns the field ID or `nullptr` if the field is not found.

A usecase for this method is searching for class fields and caching their IDs, so that they could later be used for getting/setting the fields.

This function was introduced in Qt 6.2.

### `[since 6.4]` template <typename... Args> jmethodID QJniEnvironment::findMethod(jclass clazz, const char *methodName)

Searches for an instance method of a class clazz. The method is specified by its methodName, the signature is deduced from the template parameters.

Returns the method ID or `nullptr` if the method is not found.

This function was introduced in Qt 6.4.

### `[since 6.2]` jmethodID QJniEnvironment::findMethod(jclass clazz, const char *methodName, const char *signature)

Searches for an instance method of a class clazz. The method is specified by its methodName and signature.

Returns the method ID or `nullptr` if the method is not found.

A usecase for this method is searching for class methods and caching their IDs, so that they could later be used for calling the methods.

This function was introduced in Qt 6.2.

### `[since 6.4]` template <typename T> jfieldID QJniEnvironment::findStaticField(jclass clazz, const char *fieldName)

Searches for a static field of a class clazz. The field is specified by its fieldName. The signature of the field is deduced from the template parameter.

Returns the field ID or `nullptr` if the field is not found.

This function was introduced in Qt 6.4.

### `[since 6.2]` jfieldID QJniEnvironment::findStaticField(jclass clazz, const char *fieldName, const char *signature)

Searches for a static field of a class clazz. The field is specified by its fieldName and signature.

Returns the field ID or `nullptr` if the field is not found.

A usecase for this method is searching for class fields and caching their IDs, so that they could later be used for getting/setting the fields.

This function was introduced in Qt 6.2.

### `[since 6.4]` template <typename... Args> jmethodID QJniEnvironment::findStaticMethod(jclass clazz, const char *methodName)

Searches for an instance method of a class clazz. The method is specified by its methodName, the signature is deduced from the template parameters.

Returns the method ID or `nullptr` if the method is not found.

     QJniEnvironment env;
     jclass javaClass = env.findClass("org/qtproject/example/android/CustomClass");
     jmethodID methodId = env.findStaticMethod<void, jstring>(javaClass, "staticJavaMethod");
     QJniObject javaMessage = QJniObject::fromString("findStaticMethod example");
     QJniObject::callStaticMethod<void>(javaClass,
                                        methodId,
                                        javaMessage.object<jstring>());

This function was introduced in Qt 6.4.

### `[since 6.2]` jmethodID QJniEnvironment::findStaticMethod(jclass clazz, const char *methodName, const char *signature)

Searches for a static method of a class clazz. The method is specified by its methodName and signature.

Returns the method ID or `nullptr` if the method is not found.

A usecase for this method is searching for class methods and caching their IDs, so that they could later be used for calling the methods.

     QJniEnvironment env;
     jclass javaClass = env.findClass("org/qtproject/example/android/CustomClass");
     jmethodID methodId = env.findStaticMethod(javaClass,
                                               "staticJavaMethod",
                                               "(Ljava/lang/String;)V");
     QJniObject javaMessage = QJniObject::fromString("findStaticMethod example");
     QJniObject::callStaticMethod<void>(javaClass,
                                        methodId,
                                        javaMessage.object<jstring>());

This function was introduced in Qt 6.2.

### `[static]` JNIEnv *QJniEnvironment::getJniEnv()

Returns the JNIEnv pointer for the current thread.

The current thread will be attached to the Java VM.

### `[since 6.2]` bool QJniEnvironment::isValid() const

Returns `true` if this instance holds a valid JNIEnv object.

This function was introduced in Qt 6.2.

### `[static]` JavaVM *QJniEnvironment::javaVM()

Returns the Java VM interface for the current process. Although it might be possible to have multiple Java VMs per process, Android allows only one.

### JNIEnv *QJniEnvironment::jniEnv() const

Returns the JNI Environment's `JNIEnv` pointer.

### template <typename Class> bool QJniEnvironment::registerNativeMethods(std::initializer_list<JNINativeMethod> methods)

This is an overloaded function.

Registers the Java methods in methods with the Java class represented by `Class`, and returns whether the registration was successful.

The `Class` type has to be declared within the QtJniTypes namespace using the Q_DECLARE_JNI_CLASS macro. Functions that are implemented as free C or C++ functions have to be declared using one of the Q_DECLARE_JNI_NATIVE_METHOD macros, and passed into the registration using the Q_JNI_NATIVE_METHOD macro.

     // C++ side

     Q_DECLARE_JNI_CLASS(MyJavaType, "my/java/Type")

     static void nativeFunction(JNIEnv *env, jobject thiz, jlong id)
     {
         // ...
     }
     Q_DECLARE_JNI_NATIVE_METHOD(nativeFunction)

     Q_DECL_EXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
     {
         QJniEnvironment env;
         env.registerNativeMethods<QtJniTypes::MyJavaType>({
             Q_JNI_NATIVE_METHOD(nativeFunction)
         });
     }

     // Java side
     public class MyJavaType
     {
         native public nativeFunction(long id);
     }

For functions that are implemented as static class member functions, use the macros for scoped functions instead.

     class NativeHandler
     {
         // ...
     private:
         static void handleChange(JNIEnv*, jobject, jlong id);
         Q_DECLARE_JNI_NATIVE_METHOD_IN_CURRENT_SCOPE(handleChange)
     };

     \dots
     QJniEnvironment env;
     env.registerNativeMethods<QtJniTypes::MyJavaType>({
         Q_JNI_NATIVE_SCOPED_METHOD(handleChange, NativeHandler)
     });

### bool QJniEnvironment::registerNativeMethods(const char *className, std::initializer_list<JNINativeMethod> methods)

This is an overloaded function.

Registers the native functions methods in methods for the Java class className. Returns `true` if the registration is successful, otherwise `false`.

### bool QJniEnvironment::registerNativeMethods(jclass clazz, std::initializer_list<JNINativeMethod> methods)

This is an overloaded function.

Registers the native functions methods in methods for the Java class clazz. Returns `true` if the registration is successful, otherwise `false`.

### bool QJniEnvironment::registerNativeMethods(const char *className, const JNINativeMethod[] methods, int size)

This is an overloaded function.

Registers the Java methods in the array methods of size size, each of which can call native C++ functions from class className. These methods must be registered before any attempt to call them.

Returns `true` if the registration is successful, otherwise `false`.

Each element in the methods array consists of:

- The Java method name
- Method signature
- The C++ functions that will be executed

     const JNINativeMethod methods[] =
                             {{"callNativeOne", "(I)V", reinterpret_cast<void *>(fromJavaOne)},
                             {"callNativeTwo", "(I)V", reinterpret_cast<void *>(fromJavaTwo)}};
     QJniEnvironment env;
     env.registerNativeMethods("org/qtproject/android/TestJavaClass", methods, 2);

### bool QJniEnvironment::registerNativeMethods(jclass clazz, const JNINativeMethod[] methods, int size)

This is an overloaded function.

This overload uses a previously cached jclass instance clazz.

     JNINativeMethod methods[] {{"callNativeOne", "(I)V", reinterpret_cast<void *>(fromJavaOne)},
                                {"callNativeTwo", "(I)V", reinterpret_cast<void *>(fromJavaTwo)}};
     QJniEnvironment env;
     jclass clazz = env.findClass("org/qtproject/android/TestJavaClass");
     env.registerNativeMethods(clazz, methods, 2);

### JNIEnv &QJniEnvironment::operator*() const

Returns the JNI Environment's `JNIEnv` object.

### JNIEnv *QJniEnvironment::operator->() const

Provides access to the JNI Environment's `JNIEnv` pointer.