#[repr(transparent)]
pub struct JNIEnv<'a> { /* private fields */ }
Expand description

FFI-compatible JNIEnv struct. You can safely use this as the JNIEnv argument to exported methods that will be called by java. This is where most of the magic happens. All methods on this object are wrappers around JNI functions, so the documentation on their behavior is still pretty applicable.

Exception handling

Since we’re calling into the JVM with this, many methods also have the potential to cause an exception to get thrown. If this is the case, an Err result will be returned with the error kind JavaException. Note that this will not clear the exception - it’s up to the caller to decide whether to do so or to let it continue being thrown.

null Java references

null Java references are handled by the following rules:

  • If a null Java reference is passed to a method that expects a non-null argument, an Err result with the kind NullPtr is returned.
  • If a JNI function returns null to indicate an error (e.g. new_int_array), it is converted to Err/NullPtr or, where possible, to a more applicable error type, such as MethodNotFound. If the JNI function also throws an exception, the JavaException error kind will be preferred.
  • If a JNI function may return null Java reference as one of possible reference values (e.g., get_object_array_element or get_field_unchecked), it is converted to JObject::null().

Checked and unchecked methods

Some of the methods come in two versions: checked (e.g. call_method) and unchecked (e.g. call_method_unchecked). Under the hood, checked methods perform some checks to ensure the validity of provided signatures, names and arguments, and then call the corresponding unchecked method.

Checked methods are more flexible as they allow passing class names and method/field descriptors as strings and may perform lookups of class objects and method/field ids for you, also performing all the needed precondition checks. However, these lookup operations are expensive, so if you need to call the same method (or access the same field) multiple times, it is recommended to cache the instance of the class and the method/field id, e.g.

  • in loops
  • when calling the same Java callback repeatedly.

If you do not cache references to classes and method/field ids, you will not benefit from the unchecked methods.

Calling unchecked methods with invalid arguments and/or invalid class and method descriptors may lead to segmentation fault.

Implementations

Create a JNIEnv from a raw pointer.

Safety

Expects a valid pointer retrieved from the GetEnv JNI function. Only does a null check.

Get the java version that we’re being executed from.

Load a class from a buffer of raw class data. The name of the class must match the name encoded within the class file data.

Load a class from a buffer of raw class data. The name of the class is inferred from the buffer.

Look up a class by name.

Example
let class: JClass<'a> = env.find_class("java/lang/String");

Returns the superclass for a particular class OR JObject::null() for java.lang.Object or an interface. As with find_class, takes a descriptor.

Tests whether class1 is assignable from class2.

Returns true if the object reference can be cast to the given type.

NB: Unlike the operator instanceof, function IsInstanceOf returns true for all classes if object is null.

See JNI documentation for details.

Returns true if ref1 and ref2 refer to the same Java object, or are both NULL. Otherwise, returns false.

Raise an exception from an existing object. This will continue being thrown in java unless exception_clear is called.

Examples
let _ = env.throw(("java/lang/Exception", "something bad happened"));

Defaulting to “java/lang/Exception”:

let _ = env.throw("something bad happened");

Create and throw a new exception from a class descriptor and an error message.

Example
let _ = env.throw_new("java/lang/Exception", "something bad happened");

Check whether or not an exception is currently in the process of being thrown. An exception is in this state from the time it gets thrown and not caught in a java function until exception_clear is called.

Print exception information to the console.

Clear an exception in the process of being thrown. If this is never called, the exception will continue being thrown when control is returned to java.

Abort the JVM with an error message.

Check to see if an exception is being thrown. This only differs from exception_occurred in that it doesn’t return the actual thrown exception.

Create a new instance of a direct java.nio.ByteBuffer

Example
let buf = vec![0; 1024 * 1024];
let (addr, len) = { // (use buf.into_raw_parts() on nightly)
    let buf = buf.leak();
    (buf.as_mut_ptr(), buf.len())
};
let direct_buffer = unsafe { env.new_direct_byte_buffer(addr, len) };
Safety

Expects a valid (non-null) pointer and length

Caller must ensure the lifetime of data extends to all uses of the returned ByteBuffer. The JVM may maintain references to the ByteBuffer beyond the lifetime of this JNIEnv.

Returns the starting address of the memory of the direct java.nio.ByteBuffer.

Returns the capacity (length) of the direct java.nio.ByteBuffer.

Terminology

“capacity” here means the length that was passed to Self::new_direct_byte_buffer() which does not reflect the (potentially) larger size of the underlying allocation (unlike the Vec API).

The terminology is simply kept from the original JNI API (GetDirectBufferCapacity).

Turns an object into a global ref. This has the benefit of removing the lifetime bounds since it’s guaranteed to not get GC’d by java. It releases the GC pin upon being dropped.

Create a new local reference to an object.

Specifically, this calls the JNI function NewLocalRef, which creates a reference in the current local reference frame, regardless of whether the original reference belongs to the same local reference frame, a different one, or is a global reference. In Rust terms, this method accepts a JNI reference with any valid lifetime and produces a clone of that reference with the lifetime of this JNIEnv. The returned reference can outlive the original.

This method is useful when you have a strong global reference and you can’t prevent it from being dropped before you’re finished with it. In that case, you can use this method to create a new local reference that’s guaranteed to remain valid for the duration of the current local reference frame, regardless of what later happens to the original global reference.

Lifetimes

'a is the lifetime of this JNIEnv. This method creates a new local reference with lifetime 'a.

'b is the lifetime of the original reference. It can be any valid lifetime, even one that 'a outlives or vice versa.

Think of 'a as meaning 'new and 'b as meaning 'original. (It is unfortunately not possible to actually give these names to the two lifetimes because 'a is a parameter to the JNIEnv type, not a parameter to this method.)

Example

In the following example, the ExampleError::extract_throwable method uses JNIEnv::new_local_ref to create a new local reference that outlives the original global reference:

/// An error that may be caused by either a Java exception or something going wrong in Rust
/// code.
enum ExampleError {
    /// This variant represents a Java exception.
    ///
    /// The enclosed `GlobalRef` points to a Java object of class `java.lang.Throwable`
    /// (or one of its many subclasses).
    Exception(GlobalRef),

    /// This variant represents an error in Rust code, not a Java exception.
    Other(SomeOtherErrorType),
}

impl ExampleError {
    /// Consumes this `ExampleError` and produces a `JThrowable`, suitable for throwing
    /// back to Java code.
    ///
    /// If this is an `ExampleError::Exception`, then this extracts the enclosed Java
    /// exception object. Otherwise, a new exception object is created to represent this
    /// error.
    fn extract_throwable(self, env: JNIEnv) -> jni::errors::Result<JThrowable> {
        let throwable: JObject = match self {
            ExampleError::Exception(exception) => {
                // The error was caused by a Java exception.

                // Here, `exception` is a `GlobalRef` pointing to a Java `Throwable`. It
                // will be dropped at the end of this `match` arm. We'll use
                // `new_local_ref` to create a local reference that will outlive the
                // `GlobalRef`.

                env.new_local_ref(exception.as_obj())?
            }

            ExampleError::Other(error) => {
                // The error was caused by something that happened in Rust code. Create a
                // new `java.lang.Error` to represent it.

                env.new_object(
                    "java/lang/Error",
                    "(Ljava/lang/String;)V",
                    &[
                        env.new_string(error.to_string())?.into(),
                    ],
                )?
            }
        };

        Ok(JThrowable::from(throwable))
    }
}

Creates a new auto-deleted local reference.

See also with_local_frame method that can be more convenient when you create a bounded number of local references but cannot rely on automatic de-allocation (e.g., in case of recursion, deep call stacks, permanently-attached native threads, etc.).

Deletes the local reference.

Local references are valid for the duration of a native method call. They are freed automatically after the native method returns. Each local reference costs some amount of Java Virtual Machine resource. Programmers need to make sure that native methods do not excessively allocate local references. Although local references are automatically freed after the native method returns to Java, excessive allocation of local references may cause the VM to run out of memory during the execution of a native method.

In most cases it is better to use AutoLocal (see auto_local method) or with_local_frame instead of direct delete_local_ref calls.

Creates a new local reference frame, in which at least a given number of local references can be created.

Returns Err on failure, with a pending OutOfMemoryError.

Prefer to use with_local_frame instead of direct push_local_frame/pop_local_frame calls.

See also auto_local method and AutoLocal type — that approach can be more convenient in loops.

Pops off the current local reference frame, frees all the local references allocated on the current stack frame, except the result, which is returned from this function and remains valid.

The resulting JObject will be NULL iff result is NULL.

Executes the given function in a new local reference frame, in which at least a given number of references can be created. Once this method returns, all references allocated in the frame are freed, except the one that the function returns, which remains valid.

If no new frames can be allocated, returns Err with a pending OutOfMemoryError.

See also auto_local method and AutoLocal type - that approach can be more convenient in loops.

Allocates a new object from a class descriptor without running a constructor.

Look up a method by class descriptor, name, and signature.

Example
let method_id: JMethodID =
    env.get_method_id("java/lang/String", "substring", "(II)Ljava/lang/String;");

Look up a static method by class descriptor, name, and signature.

Example
let method_id: JMethodID =
    env.get_static_method_id("java/lang/String", "valueOf", "(I)Ljava/lang/String;");

Look up the field ID for a class/name/type combination.

Example
let field_id = env.get_field_id("com/my/Class", "intField", "I");

Look up the static field ID for a class/name/type combination.

Example
let field_id = env.get_static_field_id("com/my/Class", "intField", "I");

Get the class for an object.

Call a static method in an unsafe manner. This does nothing to check whether the method is valid to call on the class, whether the return type is correct, or whether the number of args is valid for the method.

Under the hood, this simply calls the CallStatic<Type>MethodA method with the provided arguments.

Call an object method in an unsafe manner. This does nothing to check whether the method is valid to call on the object, whether the return type is correct, or whether the number of args is valid for the method.

Under the hood, this simply calls the Call<Type>MethodA method with the provided arguments.

Calls an object method safely. This comes with a number of lookups/checks. It

  • Parses the type signature to find the number of arguments and return type
  • Looks up the JClass for the given object.
  • Looks up the JMethodID for the class/name/signature combination
  • Ensures that the number of args matches the signature
  • Calls call_method_unchecked with the verified safe arguments.

Note: this may cause a java exception if the arguments are the wrong type, in addition to if the method itself throws.

Calls a static method safely. This comes with a number of lookups/checks. It

  • Parses the type signature to find the number of arguments and return type
  • Looks up the JMethodID for the class/name/signature combination
  • Ensures that the number of args matches the signature
  • Calls call_method_unchecked with the verified safe arguments.

Note: this may cause a java exception if the arguments are the wrong type, in addition to if the method itself throws.

Create a new object using a constructor. This is done safely using checks similar to those in call_static_method.

Create a new object using a constructor. Arguments aren’t checked because of the JMethodID usage.

Cast a JObject to a JList. This won’t throw exceptions or return errors in the event that the object isn’t actually a list, but the methods on the resulting map object will.

Cast a JObject to a JMap. This won’t throw exceptions or return errors in the event that the object isn’t actually a map, but the methods on the resulting map object will.

Get a JavaStr from a JString. This allows conversions from java string objects to rust strings.

This entails a call to GetStringUTFChars and only decodes java’s modified UTF-8 format on conversion to a rust-compatible string.

Panics

This call panics when given an Object that is not a java.lang.String

Get a pointer to the character array beneath a JString.

Array contains Java’s modified UTF-8.

Attention

This will leak memory if release_string_utf_chars is never called.

Unpin the array returned by get_string_utf_chars.

Safety

The behaviour is undefined if the array isn’t returned by the get_string_utf_chars function.

Examples
let s = env.new_string("test").unwrap();
let array = env.get_string_utf_chars(s).unwrap();
unsafe { env.release_string_utf_chars(s, array).unwrap() };

Create a new java string object from a rust string. This requires a re-encoding of rusts real UTF-8 strings to java’s modified UTF-8 format.

Get the length of a java array

Construct a new array holding objects in class element_class. All elements are initially set to initial_element.

This function returns a local reference, that must not be allocated excessively. See Java documentation for details.

Returns an element of the jobjectArray array.

Sets an element of the jobjectArray array.

Create a new java byte array from a rust byte slice.

Converts a java byte array to a rust vector of bytes.

Create a new java boolean array of supplied length.

Create a new java byte array of supplied length.

Create a new java char array of supplied length.

Create a new java short array of supplied length.

Create a new java int array of supplied length.

Create a new java long array of supplied length.

Create a new java float array of supplied length.

Create a new java double array of supplied length.

Copy elements of the java boolean array from the start index to the buf slice. The number of copied elements is equal to the buf length.

Errors

If start is negative or start + buf.len() is greater than array.length then no elements are copied, an ArrayIndexOutOfBoundsException is thrown, and Err is returned.

Copy elements of the java byte array from the start index to the buf slice. The number of copied elements is equal to the buf length.

Errors

If start is negative or start + buf.len() is greater than array.length then no elements are copied, an ArrayIndexOutOfBoundsException is thrown, and Err is returned.

Copy elements of the java char array from the start index to the buf slice. The number of copied elements is equal to the buf length.

Errors

If start is negative or start + buf.len() is greater than array.length then no elements are copied, an ArrayIndexOutOfBoundsException is thrown, and Err is returned.

Copy elements of the java short array from the start index to the buf slice. The number of copied elements is equal to the buf length.

Errors

If start is negative or start + buf.len() is greater than array.length then no elements are copied, an ArrayIndexOutOfBoundsException is thrown, and Err is returned.

Copy elements of the java int array from the start index to the buf slice. The number of copied elements is equal to the buf length.

Errors

If start is negative or start + buf.len() is greater than array.length then no elements are copied, an ArrayIndexOutOfBoundsException is thrown, and Err is returned.

Copy elements of the java long array from the start index to the buf slice. The number of copied elements is equal to the buf length.

Errors

If start is negative or start + buf.len() is greater than array.length then no elements are copied, an ArrayIndexOutOfBoundsException is thrown, and Err is returned.

Copy elements of the java float array from the start index to the buf slice. The number of copied elements is equal to the buf length.

Errors

If start is negative or start + buf.len() is greater than array.length then no elements are copied, an ArrayIndexOutOfBoundsException is thrown, and Err is returned.

Copy elements of the java double array from the start index to the buf slice. The number of copied elements is equal to the buf length.

Errors

If start is negative or start + buf.len() is greater than array.length then no elements are copied, an ArrayIndexOutOfBoundsException is thrown, and Err is returned.

Copy the contents of the buf slice to the java boolean array at the start index.

Copy the contents of the buf slice to the java byte array at the start index.

Copy the contents of the buf slice to the java char array at the start index.

Copy the contents of the buf slice to the java short array at the start index.

Copy the contents of the buf slice to the java int array at the start index.

Copy the contents of the buf slice to the java long array at the start index.

Copy the contents of the buf slice to the java float array at the start index.

Copy the contents of the buf slice to the java double array at the start index.

Get a field without checking the provided type against the actual field.

Set a field without any type checking.

Get a field. Requires an object class lookup and a field id lookup internally.

Set a field. Does the same lookups as get_field and ensures that the type matches the given value.

Get a static field without checking the provided type against the actual field.

Get a static field. Requires a class lookup and a field id lookup internally.

Set a static field. Requires a class lookup and a field id lookup internally.

Surrenders ownership of a Rust value to Java.

This requires an object with a long field to store the pointer.

The Rust value will be implicitly wrapped in a Box<Mutex<T>>.

The Java object will be locked before changing the field value.

Safety

It’s important to note that using this API will leak memory if Self::take_rust_field is never called so that the Rust type may be dropped.

One suggestion that may help ensure that a set Rust field will be cleaned up later is for the Java object to implement Closeable and let people use a use block (Kotlin) or try-with-resources (Java).

DO NOT make a copy of the object containing one of these fields since that will lead to a use-after-free error if the Rust type is taken and dropped multiple times from Rust.

Gets a lock on a Rust value that’s been given to a Java object.

Java still retains ownership and Self::take_rust_field will still need to be called at some point.

The Java object will be locked before reading the field value but the Java object lock will be released after the Rust Mutex lock for the field value has been taken (i.e the Java object won’t be locked once this function returns).

Safety

Checks for a null pointer, but assumes that the data it points to is valid for T.

Take a Rust field back from Java.

It sets the field to a null pointer to signal that it’s empty.

The Java object will be locked before taking the field value.

Safety

This will make sure that the pointer is non-null, but still assumes that the data it points to is valid for T.

Lock a Java object. The MonitorGuard that this returns is responsible for ensuring that it gets unlocked.

Returns underlying sys::JNIEnv interface.

Returns the Java VM interface.

Ensures that at least a given number of local references can be created in the current thread.

Bind function pointers to native methods of class according to method name and signature. For details see documentation.

Unbind all native methods of class.

Return an AutoArray of the given Java array.

The result is valid until the AutoArray object goes out of scope, when the release happens automatically according to the mode parameter.

Since the returned array may be a copy of the Java array, changes made to the returned array will not necessarily be reflected in the original array until the corresponding Release*ArrayElements JNI method is called. AutoArray has a commit() method, to force a copy of the array if needed (and without releasing it). Prefer to use the convenience wrappers: get_int_array_elements get_long_array_elements get_byte_array_elements get_boolean_array_elements get_char_array_elements get_short_array_elements get_float_array_elements get_double_array_elements And the associated AutoArray struct.

Return an AutoPrimitiveArray of the given Java primitive array.

The result is valid until the corresponding AutoPrimitiveArray object goes out of scope, when the release happens automatically according to the mode parameter.

Given that Critical sections must be as short as possible, and that they come with a number of important restrictions (see GetPrimitiveArrayCritical JNI doc), use this wrapper wisely, to avoid holding the array longer that strictly necessary. In any case, you can:

  • Use std::mem::drop explicitly, to force / anticipate resource release.
  • Use a nested scope, to release the array at the nested scope’s exit.

Since the returned array may be a copy of the Java array, changes made to the returned array will not necessarily be reflected in the original array until ReleasePrimitiveArrayCritical is called; which happens at AutoPrimitiveArray destruction.

If the given array is null, an Error::NullPtr is returned.

See also get_byte_array_elements

Trait Implementations

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.