You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
JavaVM::singleton() lets you acquire the JavaVM for the process when you know that the JavaVM singleton has been initialized (#595)
JavaVM::is_thread_attached can query whether the current thread is attached to the Java VM (#570)
AttachGuard::from_unowned added as a low-level (unsafe) way to represent a thread attachment with a raw jni_sys::Env pointer (#570)
AttachConfig exposes fine-grained control over thread attachment including Thread name, ThreadGroup and whether scoped or permanent. (#606)
JavaVM::attach_current_thread_guard is a low-level (unsafe) building block for attaching threads that exposes the AttachGuard and AttachConfig control. (#606)
JavaVM::attach_current_thread_with_config is a safe building block for attaching threads that hides the AttachGuard but exposes AttachConfig control. (#606)
JavaVM::with_local_frame added as method to borrow a Env that is already attached to the current thread, after pushing a new JNI stack frame (#570, #673)
JavaVM::with_top_local_frame_frame added to borrow a Env for the top JNI stack frame (i.e. without pushing a new JNI stack frame) (#570, #673)
Reference Type APIs
A Reference trait for all reference types like JObject, JClass, JString, enabling Global and Weak to be generic over Reference and enabling safe casting and global caching of JClass references. (#596)
Reference::lookup_class exposes a cached Global<JClass> for all Reference implementations (#612)
LoaderContext + LoaderContext::load_class for loading classes, depending on available context (#612)
Env::new_cast_global_ref acts like new_global_ref with a type cast (#612)
Env::cast_global takes an owned Global<From> and returns an owned Global<To> (#612)
Env::new_cast_local_ref acts like new_local_ref with a type cast (#612)
Env::cast_local takes an owned local reference and returns a new type-cast wrapper (owned) (#612)
Env::as_cast or Cast::new borrows any From: Reference (global or local) reference and returns a Cast<To> that will Deref into &To (#612)
Env::as_cast_unchecked returns a Cast<To> like as_cast() but without a runtime IsInstanceOf check (#669)
Env::as_cast_raw or Cast::from_raw borrows a raw jobject reference and returns a Cast<To> that will Deref into &To
Cast::new_unchecked and Cast::from_raw_unchecked let you borrow a reference with an (unsafe) type cast, with no runtime check
::cast_local() methods as a convenience for all reference types, such as let s = JString::cast_local(obj)
constnull() methods for all reference types.
Global::null() and Weak::null() construct null references (equivalent to Default::default()). (#596)
JNI Environment APIs
Env::call_nonvirtual_method and Env::call_nonvirtual_method_unchecked to call non-virtual method. (#454)
Env::to_reflected_method and Env::to_reflected_static_method for retrieving the Java reflection API instance for a method or constructor. (#579)
Env::throw_new_void provides an easy way to throw an exception that's constructed with no message argument
Env::new_object_type_array<E> lets you you instantiate a JObjectArray with a given element type like new_object_type_array::<JString>
Env::load_class supports class lookups via the current Thread context class loader, with FindClass fallback. (#674)
MethodSignature and FieldSignature types have been added for compile-time parsed JNI method and field signatures
Native Method APIs
EnvUnowned is an FFI-safe type that can be used to capture a jni_sys::Env pointer given to native methods and give it a named lifetime (this can then be temporarily upgraded to a &mut Env reference via EnvUnowned::with_env) (#570)
Outcome is like a Result with the addition of a third Panic() variant, used for careful handling of errors in native methods. (#664)
EnvOutcome represents an EnvUnowned::with_env outcome whose errors can be handle, with access to JNI, via an ErrorPolicy. (#664)
ErrorPolicy is a trait with on_error and on_panic methods that can log native method errors or throw them as exceptions. (#664)
ThrowRuntimeExAndDefault is an ErrorPolicy that throws any error as a RuntimeException (and returns a default value). (#664)
LogErrorAndDefault is an ErrorPolicy that logs errors and returns a default value. (#664)
LogContextErrorAndDefault is an ErrorPolicy that logs errors, with a given context string, and returns a default value. (#664)
String APIs
New functions for converting Rust char to and from Java char and int (#427 / #434)
JavaStr/MUTF8Chars, JNIStr, and JNIString have several new methods and traits, most notably a to_str method that converts to a regular Rust string. (#510 / #512)
JNIStr now implements Debug, PartialEq, Eq, PartialOrd, Ord and Hash (#615)
JNIString now implements Debug, PartialEq, Eq, PartialOrd, Ord, Hash and Clone (#615)
PartialEq<&JNIStr> for JNIString allows JNIStr and JNIString to be compared. (#615)
From<&JNIStr> and From<MUTF8Chars> implementations for JNIString. (#615)
JNIStr::from_cstr safely does a zero-copy cast of a CStr to a JNIStr after a const modified-utf8 encoding validation (#615,#617, #715)
JNIStr::to_bytes gives access to a &[u8] slice over the bytes of a JNI string (like CStr::to_bytes) (#615)
java.lang APIs
JClassLoader as a Reference wrapper for java.lang.ClassLoader references (#612)
JCollection, JSet and JIterator reference wrappers for java.util.Collection, java.util.Set and java.util.Iterator interfaces. (#621)
JList::remove_item for removing a given value, by-reference, from the list (instead of by index). (#713)
JList::is_empty checks if a list is empty. (#713)
JList::as_collection casts a list into a JCollection (#713)
JObjectArray::new lets you construct a JObjectArray<E> with strong element type parameterization, instead of Env::new_object_array (#657 + #688)
JObjectArray::get/set_element let you get and set array elements as methods on the array. (#654)
JPrimitiveArray::new lets you construct a JPrimitiveArray<E>, consistent with JObjectArray::new (#688)
JStackTraceElement gives access to stack frame info within a stack trace, like filename, line number etc (#657)
JString now has ::new(), ::from_str and ::from_jni_str constructor methods (#960)
JThread as a Reference wrapper for java.lang.Thread references (#612)
JThrowable::get_message is a binding for getMessage() and gives easy access to an exception message
JThrowable::get_stack_trace is a binding for getStackTrace(), returning a JObjectArray<JStackTraceElement>
Macros
The #[jni_mangle()] attribute proc macro can export an extern "system" native method with a mangled name like "Java_com_example_myMethod" so it can be automatically resolved within a shared library by the JVM (#693)
The jni_str! and jni_cstr! macros can encode a MUTF-8 &'static JNIStr or &' static CStr at compile time with full unicode support. (#696)
The jni_sig!, jni_sig_str!, jni_sig_cstr! and jni_sig_jstr! macros can parse and compile signatures like (arg0: jint, arg1: JString) -> JString into MethodSignature and FieldSignature descriptors or JNI string literals like "(ILjava/lang/String;)Ljava/lang/String;" (#697)
The native_method! macro binds a single native method to a Rust function with type safety and optionally exports it too. (#698)
The bind_java_type! macro can generate full Rust bindings for Java types (classes and interfaces) with fields, constructors, methods and native methods (#712)
Changed
JavaVM / Thread Attachment APIs
JNI version requirements are more explicit in the API and the crate now requires at least JNI >= 1.4. It needs >= 1.2 so it can check for exceptions and needs >= 1.4 to avoid runtime checks for direct byte buffers (#478)
At a low-level (unsafe), all thread attachments (not just scoped attachments) are now represented by an owned or unowned AttachGuard
AttachGuard usage is now considered unsafe since the type must be pinned to the stack (but that can't be guaranteed by the Rust type system alone).
To allow safe thread attachments (that ensure their AttachGuard is pinned to the stack), attachment APIs take a FnOnce whose &mut Env arg borrows from a hidden AttachGuard
JavaVM::attach_current_thread requests a permanent thread attachment (reducing cost of future attach_current_thread() calls)
JavaVM::attach_current_thread_for_scope requests a thread attachment that's detached after the given closure returns.
JavaVM::get_java_vm_pointer has been renamed JavaVM::get_raw for consistency.
JavaVM::new and JavaVM::with_libjvm now prevent libjvm from being unloaded. This isn't necessary for HotSpot, but other JVMs could crash if we don't do this. (#554)
Reference and Primitive Types
Make from_raw(), into_raw() and null() methods const fn. (#453)
Make from_raw() require an Env reference so the returned wrapper is guaranteed to have a local reference frame lifetime (#670)
GlobalRef and WeakRef have been renamed to Global and Weak and are now generic, parameterized, transparent wrappers over 'static reference types like Global<JClass<'static>> (no longer an Arc holding a reference and VM pointer) (#596)
Global and Weak no longer implement Clone, since JNI is required to create new reference (you'll need to explicitly use env.new_global_ref)
Global and Weak both implement Default, which will represent ::null() references (equivalent to JObject::null())
Global::into_raw replaces Global::try_into_raw and is infallible (#596)
AutoLocal has been renamed to Auto with a deprecated type alias for AutoLocal to sign post the rename.
AutoElements was simplified to only be parameterized by one lifetime for the array reference, and accepts any AsRef<JPrimitiveArray<T>> as a reference. (#508)
JObjectArray supports generic element types like JObjectArray<JString>
JavaType was simplified to not capture object names or array details (like ReturnType) since these details don't affect JValue type checks and had a hidden cost that was redundant.
JValueGen has been removed. JValue and JValueOwned are now separate, unrelated, non-generic types.
(#429) (Note: previously JValue and JValueOwned were type aliases for JValueGen, which was an internal type, but this design led to confusing error messages that made them harder to use)
JNI Environment APIs
JNIEnv is no longer a #[transparent] FFI-safe pointer wrapper and has been split into EnvUnowned (for FFI/native method args) and Env (non-FFI) (#634)
A JNIEnv type alias shows a verbose deprecation warning that explains how to migrate from JNIEnv to EnvUnowned and Env (#634)
Env::get_version has been renamed to Env::version (#478)
Env is no longer ever exposed in the API by-value can only be accessed by borrowing from a thread attachment AttachGuard.
Env implements runtime borrow checking to ensure new local references may only be associated with the top JNI stack frame
JavaVM::get_env is replaced by JavaVM::get_env_attachment which returns an AttachGuard if the current thread is attached. (#570)
The following functions are now infallible (#478):
Env::fatal_error is now guaranteed not to panic or allocate, but requires the error message to be encoded ahead of time. (#480)
Env::get_native_interface has been removed since it's redundant and Env::get_raw is more consistent with other APIs.
Env::register_native_methods is now marked unsafe since it requires all the given function pointers to be valid and match corresponding Java method signatures (568)
get_object_class borrows the Env mutably because it creates a new local reference. (#456)
get/set_*_field_unchecked have been marked as unsafe since they can lead to undefined behaviour if the given types don't match the field type (#457 + #629)
set_static_field takes a field name and signature as strings so the ID is looked up internally to ensure it's valid. (#629)
Env::get/set/take_rust_field no longer require a mutable Env reference since they don't return any new local references to the caller (#455)
Env::get_rust_field returns a MutexGuard<'local> instead of taking the &'env self lifetime (so you don't lose any &mut Env reference you have) (#675)
Env::is_assignable_from and is_instance_of no longer requires a mutable Env reference, since they don't return any new local references to the caller
Env::new_weak_ref returns a Result<Weak> and Error::ObjectFreed if the reference is null or has already been freed (instead of Result<Option<Weak>>) (#596)
Env::new_global_ref and ::new_local_ref may return Error::ObjectFreed in case a weak reference was given and the object has been freed. (#596)
Env::with_local_frame can be used with a shared &Env reference since it doesn't return a new local reference. (#673)
Env::with_local_frame_returning_local can now return any kind of local Reference, not just JObject
Env::new_object_unchecked now takes a Desc<JMethodID> for consistency/flexibility instead of directly taking a JMethodID
String APIs
JavaStr has been renamed MUTF8Chars (with a deprecated JavaStr alias) and is intended to be got via JString::mutf8_chars()
JavaStr/MUTF8Chars::from_env has been removed because it was unsound (it could cause undefined behavior and was not marked unsafe). Use JString::mutf8_chars instead. (#510 / #512)
JavaStr/MUTF8Chars::get_raw has been renamed to as_ptr. (#510 / #512)
JavaStr/MUTF8Chars, JNIStr, and JNIString no longer coerce to CStr, because using CStr::to_str will often have incorrect results. You can still get a CStr, but must use the new as_cstr method to do so. (#510 / #512)
All APIs that were accepting modified-utf8 string args via Into<JNIString>, now take AsRef<JNIStr> to avoid string copies every call. Considering that these strings are often literals for signatures or class names, most code can use jni_str!() to encode string literals at compile time, like env.find_class(jni_str!("java/lang/Foo")). (#617, #696)
JavaStr/MUTF8Chars and JString both implement Display and therefore ToString, making it even easier to get a Rust String.
Env::get_string performance was optimized by caching an expensive class lookup, and using a faster instanceof check. (#531)
Env::get_string performance was later further optimized to avoid the need for runtime type checking (#612)
Env::get_string has been deprecated in favor of JString::mutf8_chars and JString::to_string() or JString::try_to_string(env)
Class Loading APIs
The documentation for Env::find_class now recommends considering LoaderContext::load_class instead.
Desc<JClass>::lookup() is now based on LoaderContext::load_class (instead of Env::find_class), which checks for a thread context class loader by default.
Env::define_class takes a name: Option<> instead of having a separate define_unnamed_class API.
Env::define_class_bytearray was renamed to Env::define_class_jbyte and is identical to define_class except for taking a &[jbyte] slice instead of &[u8], which is a convenience if you have a JByteArray or AutoElements<JByteArray>.
Env::define_class[_jbyte] now takes a loader: AsRef<JClassLoader> instead of loader: &JObject.
java.lang APIs
JList is a simpler, transparent reference wrapper implementing Reference, like JObject, JClass, JString etc
JList::add returns the boolean returned by the Java API
JList::get and JList::remove no longer returns an Option since there's nothing special about getting a null from the Java List API.
JList::pop is deprecated since this doesn't map to standard Java List method.
JList::iter returns a JIterator instead of a JListIter
Env::get_list has been deprecated, in favor of JList::cast_local, or other generic Envcast_local/cast_global APIs.
Env::get_array_elements is deprecated in favor of JPrimitiveArray::get_elements
Env::get_array_elements_critical is deprecated in favor of JPrimitiveArray::get_elements_critical
Env::get_*_array_region and Env::set_*_array_region are deprecated in favor of JPrimitiveArray::get/set_region
Env::get_array_length is deprecated in favor of JPrimitiveArray::len and JObjectArray::len
Env::get/set_object_array_element are deprecated in favor of JObjectArray::get/set_element
Env::new_*_array methods for primitive array types (like JByteArray) take a &mut Env and a usize len, and the docs recommend using J<Type>Array::new() instead.
Miscellaneous
AutoElements[Critical]::discard() now takes ownership of the elements and drops them to release the pointer after setting the mode to NoCopyBack (#645)
Mark MonitorGuard with #[must_use] to warn when the guard is dropped accidentally (#676)
NativeMethod (used with Env::register_native_methods) is a now a transparent jni::sys::JNINativeWrapper wrapper with an unsafe::from_raw_parts constructor.
All APIs that require a JNI signature (like Env::get_method_id, Env::call_method etc) now require a pre-parsed MethodSignature or FieldSignature type instead of a raw string. This enables compile-time signature parsing via the jni_sig! macro, and avoids runtime signature parsing costs. (#714)
Env::get_string no longer leaks local references. (#528, #557)
Deadlocks on Windows when automatically detaching JNI when threads exit. Attachments are now tracked with fiber local storage so detachment happens without holding OS loader lock. (#701)
Removed
JavaVM::attach_current_thread_as_daemon (and general support for 'daemon' threads) has been removed, since their semantics are inherently poorly defined and unsafe (the distinction relates to the poorly defined limbo state after calling JavaDestroyVM, where it becomes undefined to touch the JVM) (#593)
The 'Executor' API has been removed (AttachGuard::with_env can be used instead) (#570)
Env::from_raw, Env::from_raw_unchecked and Env::unsafe_clone have been removed, since the API no longer exposes the Env type by-value, it must always be borrowed from an AttachGuard. (#570)
Error::NullDeref and Error::JavaVMMethodNotFound have been removed since they were unused.
JavaType::Method was removed since a method signature isn't a type, and all usage was being matched as unreachable or an error.
Env::define_unnamed_class was removed in favor of having the define_class[_jbyte] APIs take a name: Option instead.
Configuration
📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
If you want to rebase/retry this PR, check this box
Renovate failed to update an artifact related to this branch. You probably do not want to merge this PR as-is.
♻ Renovate will retry this branch, including artifacts, only when one of the following happens:
any of the package files in this branch needs updating, or
the branch becomes conflicted, or
you click the rebase/retry checkbox if found above, or
you rename this PR's title to start with "rebase!" to trigger it manually
The artifact failure details are included below:
File name: Cargo.lock
Command failed: cargo update --config net.git-fetch-with-cli=true --manifest-path Cargo.toml --package [email protected] --precise 0.22.0
Updating crates.io index
error: failed to select a version for the requirement `jni = "^0.21"`
candidate versions found which didn't match: 0.22.0
location searched: crates.io index
required by package `tao v0.34.1`
... which satisfies dependency `tao = "^0.34"` of package `wry v0.54.2 (/tmp/renovate/repos/github/tauri-apps/wry)`
Because you closed this PR without merging, Renovate will ignore this update (0.22). You will get a PR once a newer version is released. To ignore this dependency forever, add it to the ignoreDeps array of your Renovate config.
If you accidentally closed this PR, or if you changed your mind: rename this PR to get a fresh replacement PR.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR contains the following updates:
0.21→0.22Warning
Some dependencies could not be looked up. Check the Dependency Dashboard for more information.
Release Notes
jni-rs/jni-rs (jni)
v0.22.0Compare Source
Added
JavaVM / Thread Attachment APIs
JavaVM::singleton()lets you acquire theJavaVMfor the process when you know that theJavaVMsingleton has been initialized (#595)JavaVM::is_thread_attachedcan query whether the current thread is attached to the Java VM (#570)AttachGuard::from_unownedadded as a low-level (unsafe) way to represent a thread attachment with a rawjni_sys::Envpointer (#570)AttachConfigexposes fine-grained control over thread attachment includingThreadname,ThreadGroupand whether scoped or permanent. (#606)JavaVM::attach_current_thread_guardis a low-level (unsafe) building block for attaching threads that exposes theAttachGuardandAttachConfigcontrol. (#606)JavaVM::attach_current_thread_with_configis a safe building block for attaching threads that hides theAttachGuardbut exposesAttachConfigcontrol. (#606)JavaVM::with_local_frameadded as method to borrow aEnvthat is already attached to the current thread, after pushing a new JNI stack frame (#570, #673)JavaVM::with_top_local_frame_frameadded to borrow aEnvfor the top JNI stack frame (i.e. without pushing a new JNI stack frame) (#570, #673)Reference Type APIs
Referencetrait for all reference types likeJObject,JClass,JString, enablingGlobalandWeakto be generic overReferenceand enabling safe casting and global caching ofJClassreferences. (#596)Reference::lookup_classexposes a cachedGlobal<JClass>for allReferenceimplementations (#612)LoaderContext+LoaderContext::load_classfor loading classes, depending on available context (#612)Env::new_cast_global_refacts likenew_global_refwith a type cast (#612)Env::cast_globaltakes an ownedGlobal<From>and returns an ownedGlobal<To>(#612)Env::new_cast_local_refacts likenew_local_refwith a type cast (#612)Env::cast_localtakes an owned local reference and returns a new type-cast wrapper (owned) (#612)Env::as_castorCast::newborrows anyFrom: Reference(global or local) reference and returns aCast<To>that will Deref into&To(#612)Env::as_cast_uncheckedreturns aCast<To>likeas_cast()but without a runtimeIsInstanceOfcheck (#669)Env::as_cast_raworCast::from_rawborrows a rawjobjectreference and returns aCast<To>that will Deref into&ToCast::new_uncheckedandCast::from_raw_uncheckedlet you borrow a reference with an (unsafe) type cast, with no runtime check::cast_local()methods as a convenience for all reference types, such aslet s = JString::cast_local(obj)constnull()methods for all reference types.Global::null()andWeak::null()construct null references (equivalent toDefault::default()). (#596)JNI Environment APIs
Env::call_nonvirtual_methodandEnv::call_nonvirtual_method_uncheckedto call non-virtual method. (#454)Env::to_reflected_methodandEnv::to_reflected_static_methodfor retrieving the Java reflection API instance for a method or constructor. (#579)Env::throw_new_voidprovides an easy way to throw an exception that's constructed with no message argumentEnv::new_object_type_array<E>lets you you instantiate aJObjectArraywith a given element type likenew_object_type_array::<JString>Env::load_classsupports class lookups via the currentThreadcontext class loader, withFindClassfallback. (#674)MethodSignatureandFieldSignaturetypes have been added for compile-time parsed JNI method and field signaturesNative Method APIs
EnvUnownedis an FFI-safe type that can be used to capture ajni_sys::Envpointer given to native methods and give it a named lifetime (this can then be temporarily upgraded to a&mut Envreference viaEnvUnowned::with_env) (#570)Outcomeis like aResultwith the addition of a thirdPanic()variant, used for careful handling of errors in native methods. (#664)EnvOutcomerepresents anEnvUnowned::with_envoutcome whose errors can be handle, with access to JNI, via anErrorPolicy. (#664)ErrorPolicyis a trait withon_errorandon_panicmethods that can log native method errors or throw them as exceptions. (#664)ThrowRuntimeExAndDefaultis anErrorPolicythat throws any error as aRuntimeException(and returns a default value). (#664)LogErrorAndDefaultis anErrorPolicythat logs errors and returns a default value. (#664)LogContextErrorAndDefaultis anErrorPolicythat logs errors, with a given context string, and returns a default value. (#664)String APIs
New functions for converting Rust
charto and from Javacharandint(#427 / #434)JavaStr/MUTF8Chars,JNIStr, andJNIStringhave several new methods and traits, most notably ato_strmethod that converts to a regular Rust string. (#510 / #512)JNIStrnow implementsDebug,PartialEq,Eq,PartialOrd,OrdandHash(#615)JNIStringnow implementsDebug,PartialEq,Eq,PartialOrd,Ord,HashandClone(#615)PartialEq<&JNIStr> for JNIStringallowsJNIStrandJNIStringto be compared. (#615)From<&JNIStr>andFrom<MUTF8Chars>implementations forJNIString. (#615)JNIStr::from_cstrsafely does a zero-copy cast of aCStrto aJNIStrafter aconstmodified-utf8 encoding validation (#615,#617, #715)JNIStr::to_bytesgives access to a&[u8]slice over the bytes of a JNI string (likeCStr::to_bytes) (#615)java.lang APIs
JClassLoaderas aReferencewrapper forjava.lang.ClassLoaderreferences (#612)JCollection,JSetandJIteratorreference wrappers forjava.util.Collection,java.util.Setandjava.util.Iteratorinterfaces. (#621)JList::remove_itemfor removing a given value, by-reference, from the list (instead of by index). (#713)JList::clearallows a list to be cleared. (#713)JList::is_emptychecks if a list is empty. (#713)JList::as_collectioncasts a list into aJCollection(#713)JObjectArray::newlets you construct aJObjectArray<E>with strong element type parameterization, instead ofEnv::new_object_array(#657 + #688)JObjectArray::get/set_elementlet you get and set array elements as methods on the array. (#654)JPrimitiveArray::newlets you construct aJPrimitiveArray<E>, consistent withJObjectArray::new(#688)JStackTraceElementgives access to stack frame info within a stack trace, like filename, line number etc (#657)JStringnow has::new(),::from_strand::from_jni_strconstructor methods (#960)JThreadas aReferencewrapper forjava.lang.Threadreferences (#612)JThrowable::get_messageis a binding forgetMessage()and gives easy access to an exception messageJThrowable::get_stack_traceis a binding forgetStackTrace(), returning aJObjectArray<JStackTraceElement>Macros
#[jni_mangle()]attribute proc macro can export anextern "system"native method with a mangled name like "Java_com_example_myMethod" so it can be automatically resolved within a shared library by the JVM (#693)jni_str!andjni_cstr!macros can encode a MUTF-8&'static JNIStror&' static CStrat compile time with full unicode support. (#696)jni_sig!,jni_sig_str!,jni_sig_cstr!andjni_sig_jstr!macros can parse and compile signatures like(arg0: jint, arg1: JString) -> JStringintoMethodSignatureandFieldSignaturedescriptors or JNI string literals like "(ILjava/lang/String;)Ljava/lang/String;" (#697)native_method!macro binds a single native method to a Rust function with type safety and optionally exports it too. (#698)bind_java_type!macro can generate full Rust bindings for Java types (classes and interfaces) with fields, constructors, methods and native methods (#712)Changed
JavaVM / Thread Attachment APIs
>= 1.4. It needs>= 1.2so it can check for exceptions and needs>= 1.4to avoid runtime checks for direct byte buffers (#478)AttachGuardAttachGuardusage is now consideredunsafesince the type must be pinned to the stack (but that can't be guaranteed by the Rust type system alone).AttachGuardis pinned to the stack), attachment APIs take aFnOncewhose&mut Envarg borrows from a hiddenAttachGuardJavaVM::attach_current_threadrequests a permanent thread attachment (reducing cost of futureattach_current_thread()calls)JavaVM::attach_current_thread_for_scoperequests a thread attachment that's detached after the given closure returns.JavaVM::get_java_vm_pointerhas been renamedJavaVM::get_rawfor consistency.JavaVM::newandJavaVM::with_libjvmnow prevent libjvm from being unloaded. This isn't necessary for HotSpot, but other JVMs could crash if we don't do this. (#554)Reference and Primitive Types
Make
from_raw(),into_raw()andnull()methodsconst fn. (#453)Make
from_raw()require anEnvreference so the returned wrapper is guaranteed to have a local reference frame lifetime (#670)GlobalRefandWeakRefhave been renamed toGlobalandWeakand are now generic, parameterized, transparent wrappers over'staticreference types likeGlobal<JClass<'static>>(no longer anArcholding a reference and VM pointer) (#596)GlobalandWeakno longer implementClone, since JNI is required to create new reference (you'll need to explicitly useenv.new_global_ref)GlobalandWeakboth implementDefault, which will represent::null()references (equivalent toJObject::null())Global::into_rawreplacesGlobal::try_into_rawand is infallible (#596)AutoLocalhas been renamed toAutowith a deprecated type alias forAutoLocalto sign post the rename.AutoElementswas simplified to only be parameterized by one lifetime for the array reference, and accepts anyAsRef<JPrimitiveArray<T>>as a reference. (#508)JObjectArraysupports generic element types likeJObjectArray<JString>JavaTypewas simplified to not capture object names or array details (likeReturnType) since these details don't affectJValuetype checks and had a hidden cost that was redundant.JValueGenhas been removed.JValueandJValueOwnedare now separate, unrelated, non-generic types.(#429) (Note: previously
JValueandJValueOwnedwere type aliases forJValueGen, which was an internal type, but this design led to confusing error messages that made them harder to use)JNI Environment APIs
JNIEnvis no longer a#[transparent]FFI-safe pointer wrapper and has been split intoEnvUnowned(for FFI/native method args) andEnv(non-FFI) (#634)A
JNIEnvtype alias shows a verbose deprecation warning that explains how to migrate fromJNIEnvtoEnvUnownedandEnv(#634)Env::get_versionhas been renamed toEnv::version(#478)Envis no longer ever exposed in the API by-value can only be accessed by borrowing from a thread attachmentAttachGuard.Envimplements runtime borrow checking to ensure new local references may only be associated with the top JNI stack frameJavaVM::get_envis replaced byJavaVM::get_env_attachmentwhich returns anAttachGuardif the current thread is attached. (#570)The following functions are now infallible (#478):
Env::versionEnv::get_java_vmEnv::exception_checkEnv::exception_clearEnv::exception_describeEnv::exception_occurred(#517)Env::is_same_objectEnv::delete_local_refWeakRef::is_same_objectWeakRef::is_weak_ref_to_same_objectWeakRef::is_garbage_collectedEnv::fatal_erroris now guaranteed not to panic or allocate, but requires the error message to be encoded ahead of time. (#480)Env::get_native_interfacehas been removed since it's redundant andEnv::get_rawis more consistent with other APIs.Env::register_native_methodsis now markedunsafesince it requires all the given function pointers to be valid and match corresponding Java method signatures (568)get_object_classborrows theEnvmutably because it creates a new local reference. (#456)get/set_*_field_uncheckedhave been marked as unsafe since they can lead to undefined behaviour if the given types don't match the field type (#457 + #629)set_static_fieldtakes a field name and signature as strings so the ID is looked up internally to ensure it's valid. (#629)Env::get/set/take_rust_fieldno longer require a mutableEnvreference since they don't return any new local references to the caller (#455)Env::get_rust_fieldreturns aMutexGuard<'local>instead of taking the&'env selflifetime (so you don't lose any&mut Envreference you have) (#675)Env::is_assignable_fromandis_instance_ofno longer requires a mutableEnvreference, since they don't return any new local references to the callerEnv::new_weak_refreturns aResult<Weak>andError::ObjectFreedif the reference is null or has already been freed (instead ofResult<Option<Weak>>) (#596)Env::new_global_refand::new_local_refmay returnError::ObjectFreedin case a weak reference was given and the object has been freed. (#596)Env::with_local_framecan be used with a shared&Envreference since it doesn't return a new local reference. (#673)Env::with_local_frame_returning_localcan now return any kind of localReference, not justJObjectEnv::new_object_uncheckednow takes aDesc<JMethodID>for consistency/flexibility instead of directly taking aJMethodIDString APIs
JavaStrhas been renamedMUTF8Chars(with a deprecatedJavaStralias) and is intended to be got viaJString::mutf8_chars()JavaStr/MUTF8Chars::from_envhas been removed because it was unsound (it could cause undefined behavior and was not markedunsafe). UseJString::mutf8_charsinstead. (#510 / #512)JavaStr/MUTF8Chars::get_rawhas been renamed toas_ptr. (#510 / #512)JavaStr/MUTF8Chars,JNIStr, andJNIStringno longer coerce toCStr, because usingCStr::to_strwill often have incorrect results. You can still get aCStr, but must use the newas_cstrmethod to do so. (#510 / #512)Into<JNIString>, now takeAsRef<JNIStr>to avoid string copies every call. Considering that these strings are often literals for signatures or class names, most code can usejni_str!()to encode string literals at compile time, likeenv.find_class(jni_str!("java/lang/Foo")). (#617, #696)JavaStr/MUTF8CharsandJStringboth implementDisplayand thereforeToString, making it even easier to get a RustString.Env::get_stringperformance was optimized by caching an expensive class lookup, and using a faster instanceof check. (#531)Env::get_stringperformance was later further optimized to avoid the need for runtime type checking (#612)Env::get_stringhas been deprecated in favor ofJString::mutf8_charsandJString::to_string()orJString::try_to_string(env)Class Loading APIs
Env::find_classnow recommends consideringLoaderContext::load_classinstead.Desc<JClass>::lookup()is now based onLoaderContext::load_class(instead ofEnv::find_class), which checks for a thread context class loader by default.Env::define_classtakes aname: Option<>instead of having a separatedefine_unnamed_classAPI.Env::define_class_bytearraywas renamed toEnv::define_class_jbyteand is identical todefine_classexcept for taking a&[jbyte]slice instead of&[u8], which is a convenience if you have aJByteArrayorAutoElements<JByteArray>.Env::define_class[_jbyte]now takes aloader: AsRef<JClassLoader>instead ofloader: &JObject.java.lang APIs
JListis a simpler, transparent reference wrapper implementingReference, likeJObject,JClass,JStringetcJList::addreturns the boolean returned by the Java APIJList::getandJList::removeno longer returns anOptionsince there's nothing special about getting anullfrom the JavaListAPI.JList::popis deprecated since this doesn't map to standard JavaListmethod.JList::iterreturns aJIteratorinstead of aJListIterEnv::get_listhas been deprecated, in favor ofJList::cast_local, or other genericEnvcast_local/cast_globalAPIs.Env::get_array_elementsis deprecated in favor ofJPrimitiveArray::get_elementsEnv::get_array_elements_criticalis deprecated in favor ofJPrimitiveArray::get_elements_criticalEnv::get_*_array_regionandEnv::set_*_array_regionare deprecated in favor ofJPrimitiveArray::get/set_regionEnv::get_array_lengthis deprecated in favor ofJPrimitiveArray::lenandJObjectArray::lenEnv::get/set_object_array_elementare deprecated in favor ofJObjectArray::get/set_elementEnv::new_*_arraymethods for primitive array types (likeJByteArray) take a&mut Envand ausizelen, and the docs recommend usingJ<Type>Array::new()instead.Miscellaneous
AutoElements[Critical]::discard()now takes ownership of the elements and drops them to release the pointer after setting the mode toNoCopyBack(#645)MonitorGuardwith#[must_use]to warn when the guard is dropped accidentally (#676)NativeMethod(used withEnv::register_native_methods) is a now a transparentjni::sys::JNINativeWrapperwrapper with anunsafe::from_raw_partsconstructor.Env::get_method_id,Env::call_methodetc) now require a pre-parsedMethodSignatureorFieldSignaturetype instead of a raw string. This enables compile-time signature parsing via thejni_sig!macro, and avoids runtime signature parsing costs. (#714)Dependencies
jni-sysdependency bumped to0.4(#478)Fixed
Env::get_stringno longer leaks local references. (#528, #557)Removed
JavaVM::attach_current_thread_as_daemon(and general support for 'daemon' threads) has been removed, since their semantics are inherently poorly defined and unsafe (the distinction relates to the poorly defined limbo state after callingJavaDestroyVM, where it becomes undefined to touch the JVM) (#593)AttachGuard::with_envcan be used instead) (#570)Env::from_raw,Env::from_raw_uncheckedandEnv::unsafe_clonehave been removed, since the API no longer exposes theEnvtype by-value, it must always be borrowed from anAttachGuard. (#570)Error::NullDerefandError::JavaVMMethodNotFoundhave been removed since they were unused.JavaType::Methodwas removed since a method signature isn't a type, and all usage was being matched as unreachable or an error.Env::define_unnamed_classwas removed in favor of having thedefine_class[_jbyte]APIs take aname: Optioninstead.Configuration
📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
This PR was generated by Mend Renovate. View the repository job log.