java-spaghetti 0.2.0

Glue code to accompany the java-spaghetti code generator for binding to JVM APIs from Rust
Documentation
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
use std::marker::PhantomData;
use std::os::raw::c_char;
use std::ptr::null_mut;
use std::sync::atomic::{AtomicPtr, Ordering};

use jni_sys::*;

use crate::{AsArg, Local, ReferenceType, ThrowableType, VM};

/// FFI:  Use **Env** instead of \*const JNIEnv.  This represents a per-thread Java exection environment.
///
/// A "safe" alternative to jni_sys::JNIEnv raw pointers, with the following caveats:
///
/// 1)  A null env will result in **undefined behavior**.  Java should not be invoking your native functions with a null
///     *mut JNIEnv, however, so I don't believe this is a problem in practice unless you've bindgened the C header
///     definitions elsewhere, calling them (requiring `unsafe`), and passing null pointers (generally UB for JNI
///     functions anyways, so can be seen as a caller soundness issue.)
///
/// 2)  Allowing the underlying JNIEnv to be modified is **undefined behavior**.  I don't believe the JNI libraries
///     modify the JNIEnv, so as long as you're not accepting a *mut JNIEnv elsewhere, using unsafe to dereference it,
///     and mucking with the methods on it yourself, I believe this "should" be fine.
///
/// # Example
///
/// ### MainActivity.java
///
/// ```java
/// package com.maulingmonkey.example;
///
/// public class MainActivity extends androidx.appcompat.app.AppCompatActivity {
///     @Override
///     public native boolean dispatchKeyEvent(android.view.KeyEvent keyEvent);
///
///     // ...
/// }
/// ```
///
/// ### main_activity.rs
///
/// ```rust
/// use jni_sys::{jboolean, jobject, JNI_TRUE}; // TODO: Replace with safer equivalent
/// use java_spaghetti::Env;
///
/// #[no_mangle] pub extern "system"
/// fn Java_com_maulingmonkey_example_MainActivity_dispatchKeyEvent<'env>(
///     _env:       Env<'env>,
///     _this:      jobject, // TODO: Replace with safer equivalent
///     _key_event: jobject  // TODO: Replace with safer equivalent
/// ) -> jboolean {
///     // ...
///     JNI_TRUE
/// }
/// ```
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct Env<'env> {
    env: *mut JNIEnv,
    pd: PhantomData<&'env mut JNIEnv>,
}

static CLASS_LOADER: AtomicPtr<_jobject> = AtomicPtr::new(null_mut());

impl<'env> Env<'env> {
    pub unsafe fn from_raw(ptr: *mut JNIEnv) -> Self {
        Self {
            env: ptr,
            pd: PhantomData,
        }
    }

    pub fn as_raw(&self) -> *mut JNIEnv {
        self.env
    }

    pub fn vm(&self) -> VM {
        let jni_env = self.as_raw();
        let mut vm = null_mut();
        let err = unsafe { ((**jni_env).v1_2.GetJavaVM)(jni_env, &mut vm) };
        assert_eq!(err, JNI_OK);
        assert_ne!(vm, null_mut());
        unsafe { VM::from_raw(vm) }
    }

    // String methods

    pub unsafe fn new_string(self, chars: *const jchar, len: jsize) -> jstring {
        ((**self.env).v1_2.NewString)(self.env, chars as *const _, len)
    }

    pub unsafe fn get_string_length(self, string: jstring) -> jsize {
        ((**self.env).v1_2.GetStringLength)(self.env, string)
    }

    pub unsafe fn get_string_chars(self, string: jstring) -> *const jchar {
        ((**self.env).v1_2.GetStringChars)(self.env, string, null_mut()) as *const _
    }

    pub unsafe fn release_string_chars(self, string: jstring, chars: *const jchar) {
        ((**self.env).v1_2.ReleaseStringChars)(self.env, string, chars as *const _)
    }

    // Query Methods

    /// Set a custom class loader to use instead of JNI `FindClass` calls.
    ///
    /// When calling Java methods, `java-spaghetti` may need to resolve class names (as strings)
    /// into `jclass` pointers. The JNI API provides `FindClass` to do it. However, it is
    /// hardcoded to use the class loader for the class that called the currently-running native method.
    ///
    /// This works fine most of the time, except:
    ///
    /// - On a thread created by native code (such as with `std::thread::spawn()`), there is no
    ///   "class that called a native method" in the call stack, since the execution already started
    ///   in native code. In this case, `FindClass` falls back to the system class loader.
    /// - On Android, the system class loader can't find classes for your application, it can only find
    ///   classes from the Android frameworks.
    ///
    /// `set_class_loader` allows you to set a `ClassLoader` instance that `java-spaghetti` will use to
    /// resolve class names, by calling the `loadClass` method, instead of doing JNI `FindClass` calls.
    ///
    /// Calling this with a null `classloader` reverts back to using JNI `FindClass`.
    ///
    /// # Safety
    ///
    /// - `classloader` must be a global reference to a `java.lang.ClassLoader` instance.
    /// - The library does not take ownership of the global reference. I.e. it will not delete it if you
    ///   call `set_class_loader` with another class loader, or with null.
    pub unsafe fn set_class_loader(classloader: jobject) {
        CLASS_LOADER.store(classloader, Ordering::Relaxed);
    }

    pub unsafe fn require_class(self, class: &str) -> jclass {
        let classloader = CLASS_LOADER.load(Ordering::Relaxed);
        if !classloader.is_null() {
            let chars = class
                .trim_end_matches('\0')
                .replace('/', ".")
                .encode_utf16()
                .collect::<Vec<_>>();
            let string = unsafe { self.new_string(chars.as_ptr(), chars.len() as jsize) };

            // We still use JNI FindClass for this, to avoid a chicken-and-egg situation.
            // If the system class loader cannot find java.lang.ClassLoader, things are pretty broken!
            let cl_class = self.require_class_jni("java/lang/ClassLoader\0");
            let cl_method = self.require_method(cl_class, "loadClass\0", "(Ljava/lang/String;)Ljava/lang/Class;\0");

            let args = [jvalue { l: string }];
            let result: *mut _jobject =
                ((**self.env).v1_2.CallObjectMethodA)(self.env, classloader, cl_method, args.as_ptr());
            let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
            if !exception.is_null() {
                ((**self.env).v1_2.ExceptionClear)(self.env);
                panic!("exception happened calling loadClass()");
            } else if result.is_null() {
                panic!("loadClass() returned null");
            }

            ((**self.env).v1_2.DeleteLocalRef)(self.env, string);

            return result as jclass;
        }

        // if no classloader is set, fall back to JNI FindClass.
        self.require_class_jni(class)
    }

    unsafe fn require_class_jni(self, class: &str) -> jclass {
        debug_assert!(class.ends_with('\0'));
        let class = ((**self.env).v1_2.FindClass)(self.env, class.as_ptr() as *const c_char);
        assert!(!class.is_null());
        class
    }

    pub unsafe fn require_method(self, class: jclass, method: &str, descriptor: &str) -> jmethodID {
        debug_assert!(method.ends_with('\0'));
        debug_assert!(descriptor.ends_with('\0'));

        let method = ((**self.env).v1_2.GetMethodID)(
            self.env,
            class,
            method.as_ptr() as *const c_char,
            descriptor.as_ptr() as *const c_char,
        );
        assert!(!method.is_null());
        method
    }

    pub unsafe fn require_static_method(self, class: jclass, method: &str, descriptor: &str) -> jmethodID {
        debug_assert!(method.ends_with('\0'));
        debug_assert!(descriptor.ends_with('\0'));

        let method = ((**self.env).v1_2.GetStaticMethodID)(
            self.env,
            class,
            method.as_ptr() as *const c_char,
            descriptor.as_ptr() as *const c_char,
        );
        assert!(!method.is_null());
        method
    }

    pub unsafe fn require_field(self, class: jclass, field: &str, descriptor: &str) -> jfieldID {
        debug_assert!(field.ends_with('\0'));
        debug_assert!(field.ends_with('\0'));

        let field = ((**self.env).v1_2.GetFieldID)(
            self.env,
            class,
            field.as_ptr() as *const c_char,
            descriptor.as_ptr() as *const c_char,
        );
        assert!(!field.is_null());
        field
    }

    pub unsafe fn require_static_field(self, class: jclass, field: &str, descriptor: &str) -> jfieldID {
        debug_assert!(field.ends_with('\0'));
        debug_assert!(field.ends_with('\0'));

        let field = ((**self.env).v1_2.GetStaticFieldID)(
            self.env,
            class,
            field.as_ptr() as *const c_char,
            descriptor.as_ptr() as *const c_char,
        );
        assert!(!field.is_null());
        field
    }

    // Multi-Query Methods

    pub unsafe fn require_class_method(self, class: &str, method: &str, descriptor: &str) -> (jclass, jmethodID) {
        let class = self.require_class(class);
        (class, self.require_method(class, method, descriptor))
    }

    pub unsafe fn require_class_static_method(
        self,
        class: &str,
        method: &str,
        descriptor: &str,
    ) -> (jclass, jmethodID) {
        let class = self.require_class(class);
        (class, self.require_static_method(class, method, descriptor))
    }

    pub unsafe fn require_class_field(self, class: &str, method: &str, descriptor: &str) -> (jclass, jfieldID) {
        let class = self.require_class(class);
        (class, self.require_field(class, method, descriptor))
    }

    pub unsafe fn require_class_static_field(self, class: &str, method: &str, descriptor: &str) -> (jclass, jfieldID) {
        let class = self.require_class(class);
        (class, self.require_static_field(class, method, descriptor))
    }

    // Constructor Methods

    pub unsafe fn new_object_a<R: ReferenceType, E: ThrowableType>(
        self,
        class: jclass,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<Local<'env, R>, Local<'env, E>> {
        let result = ((**self.env).v1_2.NewObjectA)(self.env, class, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            assert!(!result.is_null());
            Ok(Local::from_raw(self, result))
        }
    }

    // Instance Methods

    pub unsafe fn call_object_method_a<R: ReferenceType, E: ThrowableType>(
        self,
        this: jobject,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<Option<Local<'env, R>>, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallObjectMethodA)(self.env, this, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else if result.is_null() {
            Ok(None)
        } else {
            Ok(Some(Local::from_raw(self, result)))
        }
    }

    pub unsafe fn call_boolean_method_a<E: ThrowableType>(
        self,
        this: jobject,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<bool, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallBooleanMethodA)(self.env, this, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result != JNI_FALSE)
        }
    }

    pub unsafe fn call_byte_method_a<E: ThrowableType>(
        self,
        this: jobject,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jbyte, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallByteMethodA)(self.env, this, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_char_method_a<E: ThrowableType>(
        self,
        this: jobject,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jchar, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallCharMethodA)(self.env, this, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_short_method_a<E: ThrowableType>(
        self,
        this: jobject,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jshort, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallShortMethodA)(self.env, this, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_int_method_a<E: ThrowableType>(
        self,
        this: jobject,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jint, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallIntMethodA)(self.env, this, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_long_method_a<E: ThrowableType>(
        self,
        this: jobject,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jlong, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallLongMethodA)(self.env, this, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_float_method_a<E: ThrowableType>(
        self,
        this: jobject,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jfloat, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallFloatMethodA)(self.env, this, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_double_method_a<E: ThrowableType>(
        self,
        this: jobject,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jdouble, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallDoubleMethodA)(self.env, this, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_void_method_a<E: ThrowableType>(
        self,
        this: jobject,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<(), Local<'env, E>> {
        ((**self.env).v1_2.CallVoidMethodA)(self.env, this, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(())
        }
    }

    // Static Methods

    pub unsafe fn call_static_object_method_a<R: ReferenceType, E: ThrowableType>(
        self,
        class: jclass,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<Option<Local<'env, R>>, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallStaticObjectMethodA)(self.env, class, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else if result.is_null() {
            Ok(None)
        } else {
            Ok(Some(Local::from_raw(self, result)))
        }
    }

    pub unsafe fn call_static_boolean_method_a<E: ThrowableType>(
        self,
        class: jclass,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<bool, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallStaticBooleanMethodA)(self.env, class, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result != JNI_FALSE)
        }
    }

    pub unsafe fn call_static_byte_method_a<E: ThrowableType>(
        self,
        class: jclass,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jbyte, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallStaticByteMethodA)(self.env, class, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_static_char_method_a<E: ThrowableType>(
        self,
        class: jclass,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jchar, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallStaticCharMethodA)(self.env, class, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_static_short_method_a<E: ThrowableType>(
        self,
        class: jclass,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jshort, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallStaticShortMethodA)(self.env, class, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_static_int_method_a<E: ThrowableType>(
        self,
        class: jclass,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jint, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallStaticIntMethodA)(self.env, class, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_static_long_method_a<E: ThrowableType>(
        self,
        class: jclass,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jlong, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallStaticLongMethodA)(self.env, class, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_static_float_method_a<E: ThrowableType>(
        self,
        class: jclass,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jfloat, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallStaticFloatMethodA)(self.env, class, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_static_double_method_a<E: ThrowableType>(
        self,
        class: jclass,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<jdouble, Local<'env, E>> {
        let result = ((**self.env).v1_2.CallStaticDoubleMethodA)(self.env, class, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(result)
        }
    }

    pub unsafe fn call_static_void_method_a<E: ThrowableType>(
        self,
        class: jclass,
        method: jmethodID,
        args: *const jvalue,
    ) -> Result<(), Local<'env, E>> {
        ((**self.env).v1_2.CallStaticVoidMethodA)(self.env, class, method, args);
        let exception = ((**self.env).v1_2.ExceptionOccurred)(self.env);
        if !exception.is_null() {
            ((**self.env).v1_2.ExceptionClear)(self.env);
            Err(Local::from_raw(self, exception))
        } else {
            Ok(())
        }
    }

    // Instance Fields

    pub unsafe fn get_object_field<R: ReferenceType>(self, this: jobject, field: jfieldID) -> Option<Local<'env, R>> {
        let result = ((**self.env).v1_2.GetObjectField)(self.env, this, field);
        if result.is_null() {
            None
        } else {
            Some(Local::from_raw(self, result))
        }
    }

    pub unsafe fn get_boolean_field(self, this: jobject, field: jfieldID) -> bool {
        let result = ((**self.env).v1_2.GetBooleanField)(self.env, this, field);
        result != JNI_FALSE
    }

    pub unsafe fn get_byte_field(self, this: jobject, field: jfieldID) -> jbyte {
        ((**self.env).v1_2.GetByteField)(self.env, this, field)
    }

    pub unsafe fn get_char_field(self, this: jobject, field: jfieldID) -> jchar {
        ((**self.env).v1_2.GetCharField)(self.env, this, field)
    }

    pub unsafe fn get_short_field(self, this: jobject, field: jfieldID) -> jshort {
        ((**self.env).v1_2.GetShortField)(self.env, this, field)
    }

    pub unsafe fn get_int_field(self, this: jobject, field: jfieldID) -> jint {
        ((**self.env).v1_2.GetIntField)(self.env, this, field)
    }

    pub unsafe fn get_long_field(self, this: jobject, field: jfieldID) -> jlong {
        ((**self.env).v1_2.GetLongField)(self.env, this, field)
    }

    pub unsafe fn get_float_field(self, this: jobject, field: jfieldID) -> jfloat {
        ((**self.env).v1_2.GetFloatField)(self.env, this, field)
    }

    pub unsafe fn get_double_field(self, this: jobject, field: jfieldID) -> jdouble {
        ((**self.env).v1_2.GetDoubleField)(self.env, this, field)
    }

    pub unsafe fn set_object_field<R: ReferenceType>(self, this: jobject, field: jfieldID, value: impl AsArg<R>) {
        ((**self.env).v1_2.SetObjectField)(self.env, this, field, value.as_arg());
    }

    pub unsafe fn set_boolean_field(self, this: jobject, field: jfieldID, value: bool) {
        ((**self.env).v1_2.SetBooleanField)(self.env, this, field, if value { JNI_TRUE } else { JNI_FALSE });
    }

    pub unsafe fn set_byte_field(self, this: jobject, field: jfieldID, value: jbyte) {
        ((**self.env).v1_2.SetByteField)(self.env, this, field, value);
    }

    pub unsafe fn set_char_field(self, this: jobject, field: jfieldID, value: jchar) {
        ((**self.env).v1_2.SetCharField)(self.env, this, field, value);
    }

    pub unsafe fn set_short_field(self, this: jobject, field: jfieldID, value: jshort) {
        ((**self.env).v1_2.SetShortField)(self.env, this, field, value);
    }

    pub unsafe fn set_int_field(self, this: jobject, field: jfieldID, value: jint) {
        ((**self.env).v1_2.SetIntField)(self.env, this, field, value);
    }

    pub unsafe fn set_long_field(self, this: jobject, field: jfieldID, value: jlong) {
        ((**self.env).v1_2.SetLongField)(self.env, this, field, value);
    }

    pub unsafe fn set_float_field(self, this: jobject, field: jfieldID, value: jfloat) {
        ((**self.env).v1_2.SetFloatField)(self.env, this, field, value);
    }

    pub unsafe fn set_double_field(self, this: jobject, field: jfieldID, value: jdouble) {
        ((**self.env).v1_2.SetDoubleField)(self.env, this, field, value);
    }

    // Static Fields

    pub unsafe fn get_static_object_field<R: ReferenceType>(
        self,
        class: jclass,
        field: jfieldID,
    ) -> Option<Local<'env, R>> {
        let result = ((**self.env).v1_2.GetStaticObjectField)(self.env, class, field);
        if result.is_null() {
            None
        } else {
            Some(Local::from_raw(self, result))
        }
    }

    pub unsafe fn get_static_boolean_field(self, class: jclass, field: jfieldID) -> bool {
        let result = ((**self.env).v1_2.GetStaticBooleanField)(self.env, class, field);
        result != JNI_FALSE
    }

    pub unsafe fn get_static_byte_field(self, class: jclass, field: jfieldID) -> jbyte {
        ((**self.env).v1_2.GetStaticByteField)(self.env, class, field)
    }

    pub unsafe fn get_static_char_field(self, class: jclass, field: jfieldID) -> jchar {
        ((**self.env).v1_2.GetStaticCharField)(self.env, class, field)
    }

    pub unsafe fn get_static_short_field(self, class: jclass, field: jfieldID) -> jshort {
        ((**self.env).v1_2.GetStaticShortField)(self.env, class, field)
    }

    pub unsafe fn get_static_int_field(self, class: jclass, field: jfieldID) -> jint {
        ((**self.env).v1_2.GetStaticIntField)(self.env, class, field)
    }

    pub unsafe fn get_static_long_field(self, class: jclass, field: jfieldID) -> jlong {
        ((**self.env).v1_2.GetStaticLongField)(self.env, class, field)
    }

    pub unsafe fn get_static_float_field(self, class: jclass, field: jfieldID) -> jfloat {
        ((**self.env).v1_2.GetStaticFloatField)(self.env, class, field)
    }

    pub unsafe fn get_static_double_field(self, class: jclass, field: jfieldID) -> jdouble {
        ((**self.env).v1_2.GetStaticDoubleField)(self.env, class, field)
    }

    pub unsafe fn set_static_object_field<R: ReferenceType>(
        self,
        class: jclass,
        field: jfieldID,
        value: impl AsArg<R>,
    ) {
        ((**self.env).v1_2.SetStaticObjectField)(self.env, class, field, value.as_arg());
    }

    pub unsafe fn set_static_boolean_field(self, class: jclass, field: jfieldID, value: bool) {
        ((**self.env).v1_2.SetStaticBooleanField)(self.env, class, field, if value { JNI_TRUE } else { JNI_FALSE });
    }

    pub unsafe fn set_static_byte_field(self, class: jclass, field: jfieldID, value: jbyte) {
        ((**self.env).v1_2.SetStaticByteField)(self.env, class, field, value);
    }

    pub unsafe fn set_static_char_field(self, class: jclass, field: jfieldID, value: jchar) {
        ((**self.env).v1_2.SetStaticCharField)(self.env, class, field, value);
    }

    pub unsafe fn set_static_short_field(self, class: jclass, field: jfieldID, value: jshort) {
        ((**self.env).v1_2.SetStaticShortField)(self.env, class, field, value);
    }

    pub unsafe fn set_static_int_field(self, class: jclass, field: jfieldID, value: jint) {
        ((**self.env).v1_2.SetStaticIntField)(self.env, class, field, value);
    }

    pub unsafe fn set_static_long_field(self, class: jclass, field: jfieldID, value: jlong) {
        ((**self.env).v1_2.SetStaticLongField)(self.env, class, field, value);
    }

    pub unsafe fn set_static_float_field(self, class: jclass, field: jfieldID, value: jfloat) {
        ((**self.env).v1_2.SetStaticFloatField)(self.env, class, field, value);
    }

    pub unsafe fn set_static_double_field(self, class: jclass, field: jfieldID, value: jdouble) {
        ((**self.env).v1_2.SetStaticDoubleField)(self.env, class, field, value);
    }
}