1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use ;
use jobject;
use crate::;
use crate;
/// A trait for types that represents a JNI reference (could be local, global or weak global as well
/// as wrapper types like [`Auto`] and [`Global`])
///
/// This trait unifies the behavior of all JNI reference types, allowing generic code to work with
/// both local and global references as well as smart-pointer-like wrappers around them.
///
/// For example, this makes it possible for APIs like [`Env::new_global_ref`] to be given a
/// non-static local reference type like [`JString<'local>`] (or an [`Auto`] wrapper) and return a
/// [`Global`] that is instead parameterized by [`JString<'static>`].
///
/// # Custom Java Type Bindings
///
/// All the built-in `jni::objects` types implement this trait, such as [`JObject`], [`JClass`] and
/// [`JString`]. You can also implement this trait for your own Java type bindings.
///
/// In addition to implementing the `Reference` trait, this is the recommended structure for custom
/// Java type bindings:
///
/// - Implement a `#[repr(transparent)]` struct wrapper around a [`JObject`].
/// - Derive `Default` for your type so that `Default::default()` returns a `null` reference
/// - Implement a corresponding `struct YourTypeAPI` that will cache a `Global<JClass>` and any
/// method/field IDs needed for your type's API (type should be `Send + Sync` as it will be stored
/// in a static cache)
/// - Implement a `YourTypeAPI::get()` method that takes a [`LoaderContext`] and returns a `'static`
/// singleton reference to the API cache, lazily loading the class and caching method/field IDs as
/// needed
/// - Implement `Reference` for your type
/// - Implement conventional reference-type APIs for `<YourType>` including: `from_raw()`,
/// `into_raw()`, `null()`, and `cast_local()`
/// - Implement constructors and methods for your type, based on `YourTypeAPI::get()` to access
/// cached class and method/field IDs
/// - Implement `AsRef<YourType<'local>>` for your type, since it's conventional for method
/// parameters to accept `impl AsRef<YourType>`
/// - Implement `Deref<Target = JObject<'local>>` so that all types can be treated as [`JObject`]s
/// - Implement `From<YourType<'local>> for IsInstanceOfType<'local>` and
/// `AsRef<IsInstanceOfType<'local>>` for any super-types (most importantly [`JObject`])
///
/// # Safety
///
/// The associated `Kind` and `GlobalKind` types must be FFI-safe, transparent wrappers around the
/// underlying JNI object reference types (such as [`jni::sys::jobject`] or [`jni::sys::jclass`])
/// and must not have any `Drop` side effects.
///
/// # Example
///
/// It would generally be recommended to use a macro to encapsulate the boilerplate of implementing
/// custom reference types, but for illustration purposes, a full implementation (including class +
/// method ID caching) could look like this:
///
/// ```rust,no_run
/// # use std::borrow::Cow;
/// # use jni::{jni_str, jni_sig};
/// # use jni::objects::{JObject, JClass, JString, Global};
/// # use jni::refs::{Reference, LoaderContext};
/// # use jni::Env;
/// # use jni::JValue;
/// # use jni::objects::JMethodID;
/// # use jni::errors::Result;
/// # use jni::sys::jobject;
///
/// /// A custom reference type for a `com.example.MyType` Java class
/// #[derive(Default, Debug)]
/// #[repr(transparent)]
/// struct MyType<'local>(JObject<'local>);
///
/// /// API cache for MyType
/// struct MyTypeAPI {
/// class: Global<JClass<'static>>,
/// my_method_id: jni::objects::JMethodID,
/// }
/// unsafe impl Send for MyTypeAPI {}
/// unsafe impl Sync for MyTypeAPI {}
///
/// impl MyTypeAPI {
/// pub fn get<'env>(
/// env: &Env<'env>,
/// loader_context: &LoaderContext,
/// ) -> Result<&'static Self> {
/// static API: std::sync::OnceLock<MyTypeAPI> = std::sync::OnceLock::new();
/// if let Some(api) = API.get() {
/// return Ok(api);
/// }
/// // Lazily load class and cache method IDs
/// // Note: we allow racing here to avoid deadlocks (e.g. through class init re-entry)
/// let api = env.with_local_frame(4, |env| -> jni::errors::Result<MyTypeAPI> {
/// let class: JClass = loader_context.load_class_for_type::<MyType>(env,false)?;
/// Ok(Self {
/// class: env.new_global_ref(&class)?,
/// my_method_id: env.get_method_id(
/// &class, jni_str!("myMethod"), jni_sig!((JString) -> JString))?,
/// })
/// })?;
/// let _ = API.set(api);
/// Ok(API.get().unwrap())
/// }
/// }
///
/// impl<'local> MyType<'local> {
/// pub fn new(env: &mut Env<'local>) -> Result<Self> {
/// let api = MyTypeAPI::get(env, &LoaderContext::default())?;
/// let obj = env.new_object(&api.class, jni_sig!("()V"), &[])?;
/// Ok(MyType(obj))
/// }
/// pub unsafe fn from_raw<'env>(env: &Env<'env>, raw: jobject) -> MyType<'env> {
/// unsafe { MyType(JObject::from_raw(env, raw)) }
/// }
/// pub fn into_raw(self) -> jobject {
/// self.0.into_raw()
/// }
/// pub const fn null() -> MyType<'static> {
/// MyType(JObject::null())
/// }
/// pub fn cast_local<'any_local>(
/// env: &mut Env<'_>,
/// obj: impl Reference + Into<JObject<'any_local>> + AsRef<JObject<'any_local>>
/// ) -> Result<MyType<'any_local>> {
/// env.cast_local::<MyType>(obj)
/// }
/// pub fn my_method<'env, 'any_local>(
/// &mut self,
/// env: &mut Env<'env>,
/// arg: impl AsRef<JString<'any_local>>
/// ) -> Result<JString<'env>> {
/// let api = MyTypeAPI::get(env, &LoaderContext::default())?;
/// let ret = unsafe {
/// env.call_method_unchecked(
/// &self.0,
/// api.my_method_id,
/// jni::signature::ReturnType::Object,
/// &[JValue::Object(arg.as_ref()).as_jni()]
/// )?.l()?
/// };
/// JString::cast_local(env, ret)
/// }
/// }
///
/// /// Safety: MyType::Kind + MyType::GlobalKind are transparent wrappers around
/// /// JObject with no Drop side effects
/// unsafe impl Reference for MyType<'_> {
/// type Kind<'local> = MyType<'local>;
/// type GlobalKind = MyType<'static>;
///
/// fn as_raw(&self) -> jni::sys::jobject {
/// self.0.as_raw()
/// }
/// fn class_name() -> std::borrow::Cow<'static, jni::strings::JNIStr> {
/// Cow::Borrowed(jni_str!("com.example.MyType"))
/// }
/// fn lookup_class<'caller>(
/// env: &jni::Env<'_>,
/// loader_context: &jni::refs::LoaderContext,
/// ) -> jni::errors::Result<
/// impl std::ops::Deref<Target = Global<JClass<'static>>> + 'caller,
/// > {
/// let api = MyTypeAPI::get(env, loader_context)?;
/// Ok(&api.class)
/// }
/// }
///
/// impl<'local> AsRef<MyType<'local>> for MyType<'local> {
/// fn as_ref(&self) -> &MyType<'local> {
/// self
/// }
/// }
/// impl<'local> std::ops::Deref for MyType<'local> {
/// type Target = JObject<'local>;
/// fn deref(&self) -> &Self::Target {
/// &self.0
/// }
/// }
/// impl<'local> AsRef<JObject<'local>> for MyType<'local> {
/// fn as_ref(&self) -> &JObject<'local> {
/// self
/// }
/// }
/// impl<'local> From<MyType<'local>> for JObject<'local> {
/// fn from(other: MyType<'local>) -> JObject<'local> {
/// other.0
/// }
/// }
/// ```
pub unsafe
/// A marker trait for Reference types that are FFI-safe transparent wrappers that match their
/// associated Kind type
// SAFETY: Kind and GlobalKind are implicitly transparent wrappers if T is
// implemented correctly / safely.
unsafe