jni
Rust bindings to the JNI
0.22.4
166M downloads/mo
#576 most downloaded on crates.io
jni-rs/jni-rs
What this package is like to depend on
Last release 5 months ago
16 Mar 2026
Ships unpredictably
gaps range from 2 weeks to 2.9 years
Some releases are documented
notes for 14 of 46 stable releases
3 versions withdrawn
withdrawn after publishing
10 years old
49 releases · first in 2016
5 releases in the last 12 months
see the full history below
Release timeline
49 releases · Nov 2016 to Mar 2026Releases
latest 49-
0.22.416 Mar 2026Release notes
Open source →Added
JCharSequencebindings forjava.lang.CharSequence(includingAsRef<JCharSequence>+.as_char_sequence()forJString) (#793)bind_java_typesupportsnon_nullqualifier/property for methods and fields to map null references toError::NullPtr(#795)bind_java_typesupports#[cfg()]attributes on methods and fields, to conditionally compile them based on features or other cfg conditions (#797)JValueOwned::check_null()+::is_null()methods for ergonomic null checks on owned (returned) values (#798)- More readable type accessors for
JValueOwned, like.into_bool()instead of.z(),.into_object()instead of.l(), etc (#798)
Fixed
jni_manglenow includesdocs/macros/jni_mangle.mdin the crate documentation, so the macro's documentation is visible on docs.rs and in IDEs (#799)
Full Changelog: v0.22.3...v0.22.4
Release notes
Open source →Added
JCharSequencebindings forjava.lang.CharSequence(includingAsRef<JCharSequence>+.as_char_sequence()forJString) (#793)bind_java_typesupportsnon_nullqualifier/property for methods and fields to map null references toError::NullPtr(#795)bind_java_typesupports#[cfg()]attributes on methods and fields, to conditionally compile them based on features or other cfg conditions (#797)JValueOwned::check_null()+::is_null()methods for ergonomic null checks on owned (returned) values (#798)- More readable type accessors for
JValueOwned, like.into_bool()instead of.z(),.into_object()instead of.l(), etc (#798)
Fixed
jni_manglenow includesdocs/macros/jni_mangle.mdin the crate documentation, so the macro's documentation is visible on docs.rs and in IDEs (#799)
-
0.22.305 Mar 2026Release notes
Open source →No functional change in this release but it fixes the docs.rs build by bumping the
simd_cesu8dep to >= 1.1.1 which no longer has an automatically-enabled "nightly" feature that may affect the docs.rs build (1.1.x is now also MSRV compatible).Note: Technically we shouldn't need this release (since the
simd_cesu8release alone will have fixed the build issue) but the other reason for the release is that the crates.io feature for queuing docs.rs rebuilds is not currently usable in our situation. docs.rs is currently fighting through a huge backlog of low-priority build jobs that will likely to take over a week to clear (we moved about 500 spots in two days, out of ~3k crates queued).Release notes
Open source →Fixed
- docs.rs build: Bumps
simd_cesu8dep to >= 1.1.1 which no longer has an automatically-enabled "nightly" feature that may affect the docs.rs build (1.1.x is now also MSRV compatible) (#790)
- docs.rs build: Bumps
-
0.22.201 Mar 2026Release notes
Open source →Note: although no breaking API change was made in this release there were some important fixes made, including a few non-trivial changes to how exceptions are handled and some important safety / soundness fixes made in the re-exported
jni-macros.For these reasons I'm going to again yank the previous 0.22.1 release after this is published, again taking into account that 0.22.1 was itself only released very recently and it should still be relatively unlikely that anyone has strictly locked in a 0.22.1 dependency.
Another benefit to yanking 0.22.1 is that it allows me to pin the
jni-macrosdependency via=0.22.2in this release so that in future releases I don't need to be worried that a newjni-macrosrelease needs to be backwards compatible with all priorjnireleases (so macros can take advantage of newjnifeatures).Hopefully things will be smoother moving forward, now that more people have been starting to update to 0.22.x and there are more people testing it.
Added
Adds bindings for the following
java.langerrors / exceptions (#767):JArrayIndexOutOfBoundsException(java.lang.ArrayIndexOutOfBoundsException)JArrayStoreException(java.lang.ArrayStoreException)JClassCircularityError(java.lang.ClassCircularityError)JClassFormatError(java.lang.ClassFormatError)JExceptionInInitializerError(java.lang.ExceptionInInitializerError)JClassNotFoundException(java.lang.ClassNotFoundException)JIllegalArgumentException(java.lang.IllegalArgumentException)JIllegalMonitorStateException(java.lang.IllegalMonitorStateException)JInstantiationException(java.lang.InstantiationException)JLinkageError(java.lang.LinkageError)JNoClassDefFoundError(java.lang.NoClassDefFoundError)JNoSuchFieldError(java.lang.NoSuchFieldError)JNoSuchMethodError(java.lang.NoSuchMethodError)JNumberFormatException(java.lang.NumberFormatException)JOutOfMemoryError(java.lang.OutOfMemoryError)JRuntimeException(java.lang.RuntimeException)JSecurityException(java.lang.SecurityException)JStringIndexOutOfBoundsException(java.lang.StringIndexOutOfBoundsException)
Added
AttachmentExceptionPolicyenum to control how Java exceptions are handled when attaching a thread (#768).Changed
- Replaced
cesu8crate withsimd_cesu8for MUTF-8 encoding, gaining SIMD acceleration andno_stdcompatibility - Removed dependency on
pastecrate (#752) attach_current_thread*APIs immediately returnErr(JavaException)if a Java exception is pending, so they don't have the side effect of clearing exceptions not thrown in the given closure (#756)- Removed
proc-macro-cratedependency from thejni-macroscrate (#758) - All internal use of JNI functions (not general calls into Java code) now catch exceptions and map to
jni::errors::Error(#762) JavaVM::attach_current_thread*APIs stash + re-throw pending exceptions so they can be run reliably, instead of bailing early with aJavaExceptionerror (e.g. needed inDropimplementations) (#768)
Fixed
Env::get_[static_]method/field_idAPIs now correctly clear + map internal exceptions toError::Method/FieldNotFounderrors (#748)Global/Weak::Dropno longer have the side effect of catching/clearing pending exceptions (#749)- Ensure that the
Env::throw*APIs actually returnErr(JavaException)as the docs state (#755) JStackTraceElementbinding fixed to lookupisNativeMethodinstead ofisNative(#760)bind_java_typeemitsexception_checksbefore JNI calls to avoid undefined behaviour from calling non-exception-safe JNI functions with pending exceptions. (#757)bind_java_typeemitsenv.assert_top()checks to ensure that any new local reference has a lifetime that's associated with the top JNI stack frame (#776)- Unsound
AsRefpointer cast foris_instance_oftypes emitted bybind_java_type(#777) bind_java_typeemitsnullobject checks to prevent calling methods or accessing fields on null objects (#781)bind_java_typeclamps the*APIstruct and native methods trait visibility to that of the binding type (#785)
New Contributors
- @adityagiri3600 made their first contribution in #742
- @sehnryr made their first contribution in #786
Full Changelog: v0.22.1...v0.22.2
Release notes
Open source →Note: although no breaking API change was made in this release there were some important fixes made, including a few non-trivial changes to how exceptions are handled and some important safety / soundness fixes made in the re-exported
jni-macros.For these reasons I'm going to again yank the previous 0.22.1 release after this is published, again taking into account that 0.22.1 was itself only released very recently and it should still be relatively unlikely that anyone has strictly locked in a 0.22.1 dependency.
Another benefit to yanking 0.22.1 is that it allows me to pin the
jni-macrosdependency via=0.22.2in this release so that in future releases I don't need to be worried that a newjni-macrosrelease needs to be backwards compatible with all priorjnireleases (so macros can take advantage of newjnifeatures).Hopefully things will be smoother moving forward, now that more people have been starting to update to 0.22.x and there are more people testing it.
Added
Adds bindings for the following
java.langerrors / exceptions (#767):JArrayIndexOutOfBoundsException(java.lang.ArrayIndexOutOfBoundsException)JArrayStoreException(java.lang.ArrayStoreException)JClassCircularityError(java.lang.ClassCircularityError)JClassFormatError(java.lang.ClassFormatError)JExceptionInInitializerError(java.lang.ExceptionInInitializerError)JClassNotFoundException(java.lang.ClassNotFoundException)JIllegalArgumentException(java.lang.IllegalArgumentException)JIllegalMonitorStateException(java.lang.IllegalMonitorStateException)JInstantiationException(java.lang.InstantiationException)JLinkageError(java.lang.LinkageError)JNoClassDefFoundError(java.lang.NoClassDefFoundError)JNoSuchFieldError(java.lang.NoSuchFieldError)JNoSuchMethodError(java.lang.NoSuchMethodError)JNumberFormatException(java.lang.NumberFormatException)JOutOfMemoryError(java.lang.OutOfMemoryError)JRuntimeException(java.lang.RuntimeException)JSecurityException(java.lang.SecurityException)JStringIndexOutOfBoundsException(java.lang.StringIndexOutOfBoundsException)
Added
AttachmentExceptionPolicyenum to control how Java exceptions are handled when attaching a thread (#768).Changed
- Replaced
cesu8crate withsimd_cesu8for MUTF-8 encoding, gaining SIMD acceleration andno_stdcompatibility - Removed dependency on
pastecrate (#752) attach_current_thread*APIs immediately returnErr(JavaException)if a Java exception is pending, so they don't have the side effect of clearing exceptions not thrown in the given closure (#756)- Removed
proc-macro-cratedependency from thejni-macroscrate (#758) - All internal use of JNI functions (not general calls into Java code) now catch exceptions and map to
jni::errors::Error(#762) JavaVM::attach_current_thread*APIs stash + re-throw pending exceptions so they can be run reliably, instead of bailing early with aJavaExceptionerror (e.g. needed inDropimplementations) (#768)
Fixed
Env::get_[static_]method/field_idAPIs now correctly clear + map internal exceptions toError::Method/FieldNotFounderrors (#748)Global/Weak::Dropno longer have the side effect of catching/clearing pending exceptions (#749)- Ensure that the
Env::throw*APIs actually returnErr(JavaException)as the docs state (#755) JStackTraceElementbinding fixed to lookupisNativeMethodinstead ofisNative(#760)bind_java_typeemitsexception_checksbefore JNI calls to avoid undefined behaviour from calling non-exception-safe JNI functions with pending exceptions. (#757)bind_java_typeemitsenv.assert_top()checks to ensure that any new local reference has a lifetime that's associated with the top JNI stack frame (#776)- Unsound
AsRefpointer cast foris_instance_oftypes emitted bybind_java_type(#777) bind_java_typeemitsnullobject checks to prevent calling methods or accessing fields on null objects (#781)bind_java_typeclamps the*APIstruct and native methods trait visibility to that of the binding type (#785)
-
0.22.120 Feb 2026 withdrawnRelease notes
Open source →This release fixes several issues found shortly after releasing 0.22.0 which unfortunately required a few breaking changes.
Instead of bumping to 0.23 though, the assumption 🤞 is that no one will yet be depending on the recently-released
0.22.0 and so we can yank that and have this represent the first 0.22.x release.In particular this addresses the following issues:
- Don't allow JNI calls with pending exceptions (undefined behaviour) #731
- JavaVM::attach_current_thread* should catch + clear exceptions #732
- Env::throw* APIs should return Err(Error::JavaException) #737
Added
Env::exception_catchprovides a convenient way of catching pending Java exceptions and mapping them toError::CaughtJavaException(#736)AttachGuard::detach_with_catchlets you explicitly detach/drop a guard (like::detach()) and catch any pending Java exception as aError::CaughtJavaException(#736).JClass::get_namelets you query the binary name for a class, such asjava.lang.String(#736)
Changed
The following APIs have had to be made fallible again, in order to safely check for pending exceptions before calling
JNI functions that are not documented as being safe to call with a pending exception:Env::get_java_vm(GetJavaVMis not exception safe)Env::version(GetVersionis not exception safe)Env::is_same_object(IsSameObjectis not exception safe)Weak::is_garbage_collected(based onEnv::is_same_object)Weak::is_same_object(deprecated) and (based on
Env::is_same_object)Weak::is_weak_ref_to_same_object (deprecated)(based on
Env::is_same_object)
Note: These are a breaking change.
Fixed in #733
JavaVM::attach_current_thread*APIs all finish by callingAttachGuard::detach_with_catchto clear pending Java exceptions - mapping toError::CaughtJavaException(#736)Env::throw*APIs now returnError::JavaExceptionafter throwing and creating a pending exception that must be handled before using JNI further (#738)
Release notes
Open source →Note: This release fixes several issues found in 0.22.0 which unfortunately required a few breaking changes. Instead of bumping to 0.23 though, the assumption is that no one will yet be depending on the recently-released 0.22.0 and so we can yank that and have this represent the first 0.22.x release.
Added
Env::exception_catchprovides a convenient way of catching pending Java exceptions and mapping them toError::CaughtJavaException(#736)AttachGuard::detach_with_catchlets you explicitly detach/drop a guard (like::detach()) and catch any pending Java exception as aError::CaughtJavaException(#736).JClass::get_namelets you query the binary name for a class, such asjava.lang.String(#736)
Changed
The following APIs have had to be made fallible again, in order to safely check for pending exceptions before calling JNI functions that are not documented as being safe to call with a pending exception:
Env::get_java_vm(GetJavaVMis not exception safe)Env::version(GetVersionis not exception safe)Env::is_same_object(IsSameObjectis not exception safe)Weak::is_garbage_collected(based onEnv::is_same_object)Weak::is_same_object(deprecated) and (based onEnv::is_same_object)Weak::is_weak_ref_to_same_object (deprecated)(based onEnv::is_same_object)
Note: These are a breaking change.
Fixed in #733
JavaVM::attach_current_thread*APIs all finish by callingAttachGuard::detach_with_catchto clear pending Java exceptions - mapping toError::CaughtJavaException(#736)Env::throw*APIs now returnError::JavaExceptionafter throwing and creating a pending exception that must be handled before using JNI further (#738)
-
0.22.017 Feb 2026 withdrawnRelease notes
Open source →The 0.22 release significantly improves safety and ergonomics through changes to thread attachment, environment handling, and the addition of compile-time macros for JNI strings, signatures as well as full Java type bindings.
Please see the jni 0.22 Migration Guide for guidance on how to update from jni 0.21
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
- A
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 signatures
Native 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
- The
#[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) - The
jni_str!andjni_cstr!macros can encode a MUTF-8&'static JNIStror&' static CStrat compile time with full unicode support. (#696) - The
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) - 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.2so it can check for exceptions and needs>= 1.4to 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 AttachGuardusage is now consideredunsafesince 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
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: previouslyJValueandJValueOwnedwere 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
-
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 frame -
JavaVM::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_collected
-
Env::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 caller -
Env::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 justJObject -
Env::new_object_uncheckednow takes aDesc<JMethodID>for consistency/flexibility instead of directly taking aJMethodID
String 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)- All APIs that were accepting modified-utf8 string args via
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
- The documentation for
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)- Mark
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.- All APIs that require a JNI signature (like
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)- 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 callingJavaDestroyVM, where it becomes undefined to touch the JVM) (#593)- The 'Executor' API has been removed (
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.
New Contributors
- @cakekindel made their first contribution in #445
- @koutheir made their first contribution in #453
- @Rabbit0w0 made their first contribution in #454
- @jerrinot made their first contribution in #490
- @Jake-Shadle made their first contribution in #489
- @tisonkun made their first contribution in #497
- @ssrlive made their first contribution in #559
- @complexspaces made their first contribution in #552
- @olivergillespie made their first contribution in #531
- @emergent made their first contribution in #544
- @elichai made their first contribution in #561
- @akonradi-signal made their first contribution in #579
- @atouchet made their first contribution in #578
- @louwers made their first contribution in #583
- @StDymphna made their first contribution in #618
- @pr2502 made their first contribution in #676
- @moretea made their first contribution in #679
Full Changelog: v0.21.1...v0.22.0
Release notes
Open 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
- A
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 signatures
Native 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
- The
#[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) - The
jni_str!andjni_cstr!macros can encode a MUTF-8&'static JNIStror&' static CStrat compile time with full unicode support. (#696) - The
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) - 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.2so it can check for exceptions and needs>= 1.4to 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 AttachGuardusage is now consideredunsafesince 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
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: previouslyJValueandJValueOwnedwere 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 frame -
JavaVM::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_collected
-
Env::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 caller -
Env::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 justJObject -
Env::new_object_uncheckednow takes aDesc<JMethodID>for consistency/flexibility instead of directly taking aJMethodID
String 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)- All APIs that were accepting modified-utf8 string args via
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
- The documentation for
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)- Mark
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.- All APIs that require a JNI signature (like
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)- 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 callingJavaDestroyVM, where it becomes undefined to touch the JVM) (#593)- The 'Executor' API has been removed (
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.
-
0.21.115 Mar 2023 -
0.21.013 Feb 2023Release notes
Open source →This release makes extensive breaking changes in order to improve safety. Most projects that use this library will need to be changed. Please see the migration guide.
Added
JavaStr::into_raw()which drops theJavaStrand releases ownership of the raw string pointer (#374)JavaStr::from_raw()which takes ownership of a raw string pointer to create aJavaStr(#374)JNIEnv::get_string_uncheckedis a cheaper,unsafealternative toget_stringthat doesn't check the given object is ajava.lang.Stringinstance. (#328)WeakRefandJNIEnv#new_weak_ref. (#304)define_class_bytearraymethod that takes anAutoElements<jbyte>rather than a&[u8](#244)JObjectnow has anas_rawmethod that borrows theJObjectinstead of taking ownership likeinto_raw. Needed becauseJObjectno longer has theCopytrait. (#392)JavaVM::destroy()(unsafe) as a way to try and unload aJavaVMon supported platforms (#391)JavaVM::detach_current_thread()(unsafe) as a way to explicitly detach a thread (normally this is automatic on thread exit). Needed to detach daemon threads manually if usingJavaVM::destroy()(#391)JPrimitiveArray<T: TypeArray>and type-specific aliases likeJByteArray,JIntArrayetc now provide safe, reference wrappers for thesystypesjarrayandjbyteArrayetc with a lifetime likeJObject(#400)JObjectArrayprovides a reference wrapper for ajobjectArraywith a lifetime likeJObject. (#400)AutoElementsandAutoElementsCritical(previouslyAutoArray/AutoPrimitiveArray) implementDeref<Target=[T]>andDerefMutso array elements can be accessed via slices without needing additionalunsafecode. (#400)AsJArrayRawtrait which enablesJNIEnv::get_array_length()to work withJPrimitiveArrayorJObjectArraytypes (#400)InitArgsBuildernow hastry_optionandoption_encodedmethods. (#414)
Changed
JNIEnv::get_stringchecks that the given object is ajava.lang.Stringinstance to avoid undefined behaviour from the JNI implementation potentially aborting the program. (#328)JNIEnv::call_*method_uncheckedwas markedunsafe, as passing improper argument types, or a bad number of arguments, can cause a JVM crash. (#385)- The
JNIEnv::new_object_uncheckedfunction now takes arguments as&[jni::sys::jvalue]to avoid allocating, putting it inline with changes toJniEnv::call_*_uncheckedfrom 0.20.0 (#382) - The
get_superclassfunction now returns an Option instead of a null pointer if the class has no superclass (#151) - The
invocationfeature now locates the JVM implementation dynamically at runtime (via thejava-locatorcrate by default) instead of linking with the JVM at build time (#293) - Most
JNIEnvmethods now require&mut self. This improves safety by preventingJObjects from getting an invalid lifetime. Most native method implementations (that is,#[no_mangle] extern "system" fns) must now make theJNIEnvparametermut. See the example on the crate documentation. (#392) JByteBuffer,JClass,JNIEnv,JObject,JString, andJThrowableno longer have theCloneorCopytraits. This improves safety by preventing object references from being used after the JVM deletes them. Most functions that take one of these types as a parameter (exceptextern fns that are directly called by the JVM) should now borrow it instead, e.g.&JObjectinstead ofJObject. (#392)AutoLocalis now generic in the type of object reference (JString, etc). (#392)- The closure passed to
JNIEnv::with_local_framemust now take a&mut JNIEnvparameter, which has a different lifetime. This improves safety by preventing local references from escaping the closure, which would cause a use-after-free bug.Executor::with_attachedandExecutor::with_attached_capacityhave been similarly changed. (#392) - The closure passed to
JNIEnv::with_local_framecan now return a genericResult<T, E>so long as the error implementsFrom<jni::errors::Error>(#399) JNIEnv::with_local_framenow returns the same type that the given closure returns (#399)JNIEnv::with_local_frameno longer supports returning a local reference directly to the calling scope (seewith_local_frame_returning_local) (#399)Executor::with_attachedandExecutor::with_attached_capacityhave been changed in the same way asJNIEnv::with_local_frame(they are thin wrappers) (#399)Desc,JNIEnv::pop_local_frame, andTypeArrayare nowunsafe. (#392)- The
Desctrait now has an associated typeOutput. Many implementations now returnAutoLocal, so if you callDesc::lookupyourself and then callas_rawon the returned object, make sure theAutoLocalisn't dropped too soon (see theDesc::lookupdocumentation for examples). (#392) - The
Desc<JClass>trait is no longer implemented forJObjector&JObject. The previous implementation that called.get_object_class()was surprising and a simpler cast would make it easy to mistakenly pass instances where a class is required. (#118) - Named lifetimes in the documentation have more descriptive names (like
'localinstead of'a). The new naming convention is explained in theJNIEnvdocumentation. (#392) - Object reference types (
JObject,JClass,AutoLocal,GlobalRef, etc) now implementAsRef<JObject>andDeref<Target = JObject>. Typed wrappers likeJClassalso implementInto<JObject>, butGlobalRefdoes not. (#392) - Most
JListandJMapmethods now require a&mut JNIEnvparameter.JListIterandJMapIterno longer implementIterator, and instead have anextmethod that requires a&mut JNIEnvparameter (usewhile letloops instead offor). (#392) JValuehas been changed in several ways: (#392)- It is now a generic type named
JValueGen.JValueis now a type alias forJValueGen<&JObject>, that is, it borrows an object reference.JValueOwnedis a type alias forJValueGen<JObject>, that is, it owns an object reference. JValueOwneddoes not have theCopytrait.- The
to_jnimethod is now namedas_jni, and it borrows theJValueGeninstead of taking ownership. JObjectcan no longer be converted directly toJValue, which was commonly done when calling Java methods or constructors. Instead ofobj.into(), use(&obj).into().
- It is now a generic type named
- All
JNIEnvarray APIs now work in terms ofJPrimitiveArrayandJObjectArray(reference wrappers with a lifetime) instead ofsystypes likejarrayandjbyteArray(#400) AutoArrayandAutoPrimitiveArrayhave been renamedAutoElementsandAutoElementsCriticalto show their connection and differentiate from newJPrimitiveArrayAPI (#400)get_primitive_array_criticalis nowunsafeand has been renamed toget_array_elements_critical(consistent with the rename ofAutoPrimitiveArray) with more detailed safety documentation (#400)get_array_elementsis now alsounsafe(for many of the same reasons asget_array_elements_critical) and has detailed safety documentation (#400)AutoArray/AutoArrayCritical::size()has been replaced with.len()which can't fail and returns ausize(#400)- The
TypeArraytrait is now a private / sealed trait, that is considered to be an implementation detail for theAutoArrayAPI. JvmErrorhas several more variants and is nownon_exhaustive. (#414)InitArgsBuilder::optionraises an error on Windows if the string is too long. The limit is currently 1048576 bytes. (#414)
Fixed
- Trying to use an object reference after it has been deleted now causes a compile error instead of undefined behavior. As a result, it is now safe to use
AutoLocal,JNIEnv::delete_local_ref, andJNIEnv::with_local_frame. (Most of the limitations added in #392, listed above, were needed to make this work.) (#381, #392) - Class lookups via the
Desctrait now returnAutoLocals, which prevents them from leaking. (#109, #392) InitArgsBuilder::optionproperly encodes non-ASCII characters on Windows. (#414)
Removed
get_string_utf_charsandrelease_string_utf_charsfromJNIEnv(SeeJavaStr::into_raw()andJavaStr::from_raw()instead) (#372)- All
JNIEnv::get_<type>_array_elements()methods have been removed as redundant since they would all be equivalent toget_array_elements()with the introduction ofJPrimitiveArray(#400)
-
0.20.018 Oct 2022Release notes
Open source →Added
Defaulttrait implemented forJObject,JString,JClass, andJByteBuffer(#199)Debugtrait implemented forJavaVM,GlobalRef,GlobalRefGuard,JStaticMethodIDandReleaseMode(#345)ReturnTypefor specifying object return types without a String allocation. (#329)
Changed
- The
release_string_utf_charsfunction has been marked as unsafe. (#334) - Mark
JNIEnv::new_direct_byte_bufferasunsafe(#320) JNIEnv::new_direct_byte_buffernow takes a raw pointer and size instead of a slice (#351 and #364)JNIEnv::direct_buffer_addressreturns a raw pointer instead of a slice (#364)- The lifetime of
AutoArrayis no longer tied to the lifetime of a particularJNIEnvreference. (#302) - Relaxed lifetime restrictions on
JNIEnv::new_local_ref. Now it can be used to create a local reference from a global reference. (#301 / #319) JMethodIDandJStaticMethodIDimplementSend+Syncand no longer has a lifetime parameter, making method IDs cacheable (with a documented 'Safety' note about ensuring they remain valid). (#346)JFieldIDandJStaticFieldIDimplementSend+Syncand no longer has a lifetime parameter, making field IDs cacheable (with a documented 'Safety' note about ensuring they remain valid). (#346)- The
call_*_method_uncheckedfunctions now takejni:sys::jvaluearguments to avoid allocating aVecon each call to map + collectJValues assys:jvalues (#329) - The
Fromtrait implementations convertingjni_systypes likejobjecttoJObjecthave been replaced withunsafe::from_rawfunctions and corresponding::into_rawmethods. Existing::into_innerAPIs were renamed::into_rawfor symmetry. (#197) - The APIs
JNIEnv::set_rust_field,JNIEnv::get_rust_fieldandJNIEnv::take_rust_fieldhave been marked asunsafe(#219)
-
0.19.006 Feb 2021Release notes
Open source →Added
AutoArrayand genericget_array_elements(), along withget_<type>_array_elementshelpers. (#287)size()method toAutoArrayandAutoPrimitiveArray. (#278 / #287)discard()method toAutoArrayandAutoPrimitiveArray. (#275 / #287)
Changed
- Removed AutoPrimitiveArray::commit(). (#290)
AutoByte/PrimitiveArray.commit()now returnsResult. (#275)- Removed methods get/release/commit_byte/primitive_array_{elements|critical}. (#281)
- Renamed methods get_auto_byte/long/primitive_array_{elements|critical} to get_byte/long/primitive_array_{elements|critical}. (#281)
-
0.18.025 Oct 2020Release notes
Open source →Added
JNIEnv#define_unnamed_classfunction that allows loading a class without specifying its name. The name is inferred from the class data. (#246)SetStatic<type>Field. (#248)TryFrom<JValue>for types inside JValue variants (#264).- Implemented Copy for JNIEnv (#255).
repr(transparent)attribute to JavaVM struct (#259)
Changed
- Switch from
error-chaintothiserror, making all errorsSend. Also, support all JNI errors in thejni_error_code_to_resultfunction and add more information to theInvalidArgListerror. (#242)
-
0.17.030 Jun 2020Release notes
Open source →Added
- Get/ReleaseByteArrayElements, and Get/ReleasePrimitiveArrayCritical. (#237)
-
0.16.024 Mar 2020Release notes
Open source →Fixed
- Java VM instantiation with some MacOS configurations. (#220, #229, #230).
-
0.15.029 Feb 2020Release notes
Open source →Added
- Ability to pass object wrappers that are convertible to
JObjectas arguments to the majority of JNIEnv methods without explicit conversion. (#213) JNIEnv#is_same_objectimplementation. (#213)JNIEnv#register_native_methods. (#214)- Conversion from
Into<JObject>toJValue::Object.
Fixed
- Passing
nullas class loader todefine_classmethod now allowed according to the JNI specification. (#225)
- Ability to pass object wrappers that are convertible to
-
0.14.031 Oct 2019Release notes
Open source →Changed
- Relaxed some lifetime restrictions in JNIEnv to support the case when method, field ids; and global references to classes have a different (larger) lifetime than JNIEnv. (#209)
-
0.13.127 Aug 2019 -
0.13.005 Jul 2019Release notes
Open source →0.13 brings major improvements in thread management, allowing to attach the native threads permanently and safely;
Executorfor extra convenience and safety; and other improvements and fixes.:warning: If your code attaches native threads — make sure to check the updated documentation of JavaVM to learn about the new features!
Added
JavaVM::attach_current_thread_permanentlymethod, which attaches the current thread and detaches it when the thread finishes. Daemon threads attached withJavaVM::attach_current_thread_as_daemonalso automatically detach themselves when finished. The number of currently attached threads may be acquired usingJavaVM::threads_attachedmethod. (#179, #180)Executor— a simple thread attachment manager which helps to safely execute a closure in attached thread context and to automatically free created local references at closure exit. (#186)
Changed
- The default JNI API version in
InitArgsBuilderfrom V1 to V8. (#178) - Extended the lifetimes of
AutoLocalto make it more flexible. (#190) - Default exception type from checked
java.lang.Exceptionto uncheckedjava.lang.RuntimeException. It is used implicitly whenJNIEnv#throwis invoked with exception message:env.throw("Exception message"); however, for efficiency reasons, it is recommended to specify the exception type explicitly and usethrow_new:env.throw_new(exception_type, "Exception message"). (#194)
Fixed
- Native threads attached with
JavaVM::attach_current_thread_as_daemonnow automatically detach themselves on exit, preventing Java Thread leaks. (#179) - Local reference leaks in
JList,JMapandJMapIter. (#190, #191)
-
0.12.324 May 2019Nothing published for this version
-
0.12.202 May 2019Nothing published for this version
-
0.12.127 Apr 2019Nothing published for this version
-
0.12.001 Apr 2019Nothing published for this version
-
0.11.021 Feb 2019Nothing published for this version
-
0.10.211 Sep 2018Nothing published for this version
-
0.10.123 Apr 2018Nothing published for this version
-
0.10.006 Apr 2018Nothing published for this version
-
0.9.312 Jan 2018Nothing published for this version
-
0.9.212 Jan 2018Nothing published for this version
-
0.9.112 Jan 2018 withdrawnNothing published for this version
-
0.9.010 Jan 2018Nothing published for this version
-
0.8.106 Dec 2017Nothing published for this version
-
0.8.001 Dec 2017Nothing published for this version
-
0.7.221 Nov 2017Nothing published for this version
-
0.7.120 Nov 2017Nothing published for this version
-
0.7.007 Nov 2017Nothing published for this version
-
0.6.125 Sep 2017Nothing published for this version
-
0.6.022 Sep 2017Nothing published for this version
-
0.5.315 Sep 2017Nothing published for this version
-
0.5.230 Aug 2017Nothing published for this version
-
0.5.101 Aug 2017Nothing published for this version
-
0.5.026 Jun 2017Nothing published for this version
-
0.4.423 Jun 2017Nothing published for this version
-
0.4.323 Jun 2017Nothing published for this version
-
0.4.213 Jun 2017Nothing published for this version
-
0.4.112 Jun 2017Nothing published for this version
-
0.4.031 Mar 2017Nothing published for this version
-
0.3.109 Jan 2017Nothing published for this version
-
0.3.028 Dec 2016Nothing published for this version
-
0.2.029 Nov 2016Nothing published for this version
-
0.1.108 Nov 2016Nothing published for this version
-
0.1.008 Nov 2016Nothing published for this version