[go: up one dir, main page]

jni 0.4.0

Rust bindings to the JNI
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
use std::str;

use std::marker::PhantomData;

use std::iter::IntoIterator;

use std::sync::Mutex;
use std::sync::MutexGuard;

use errors::*;

use sys::{self, jvalue, jint, jsize, jbyte, jboolean, jbyteArray};
use std::os::raw::c_char;

use strings::JNIString;
use strings::JavaStr;

use objects::JMap;
use objects::JValue;
use objects::JClass;
use objects::JObject;
use objects::JString;
use objects::JThrowable;
use objects::JMethodID;
use objects::JStaticMethodID;
use objects::JFieldID;
use objects::GlobalRef;

use descriptors::Desc;

use signature::TypeSignature;
use signature::JavaType;
use signature::Primitive;

/// FFI-compatible JNIEnv struct. You can safely use this as the JNIEnv argument
/// to exported methods that will be called by java. This is where most of the
/// magic happens. All methods on this object are wrappers around JNI functions,
/// so the documentation on their behavior is still pretty applicable.
///
/// Since we're calling into the JVM with this, many methods also have the
/// potential to cause an exception to get thrown. If this is the case, an `Err`
/// result will be returned with the error kind `JavaException`. Note that this
/// will _not_ clear the exception - it's up to the caller to decide whether to
/// do so or to let it continue being thrown.
///
/// Because null pointers are a thing in Java, this also converts them to an
/// `Err` result with the kind `NullPtr`. This may occur when either a null
/// argument is passed to a method or when a null would be returned. Where
/// applicable, the null error is changed to a more applicable error type, such
/// as `MethodNotFound`.
#[repr(C)]
pub struct JNIEnv<'a> {
    internal: *mut sys::JNIEnv,
    lifetime: PhantomData<&'a ()>,
}

impl<'a> From<*mut sys::JNIEnv> for JNIEnv<'a> {
    fn from(other: *mut sys::JNIEnv) -> Self {
        JNIEnv {
            internal: other,
            lifetime: PhantomData,
        }
    }
}

impl<'a> JNIEnv<'a> {
    /// Get the java version that we're being executed from. This is encoded and
    /// will need to be checked against constants from the sys module.
    ///
    /// TODO: convert this to something more usable.
    pub fn get_version(&self) -> Result<jint> {
        Ok(unsafe { jni_unchecked!(self.internal, GetVersion) })
    }

    /// Define a new java class. See the JNI docs for more details - I've never
    /// had occasion to use this and haven't researched it fully.
    pub fn define_class<S>(&self, name: S, loader: JObject, buf: &[u8]) -> Result<JClass>
        where S: Into<JNIString>
    {
        non_null!(loader, "define_class loader argument");
        let name = name.into();
        let class = jni_call!(self.internal,
                              DefineClass,
                              name.as_ptr(),
                              loader.into_inner(),
                              buf.as_ptr() as *const jbyte,
                              buf.len() as jsize);
        Ok(class)
    }

    /// Look up a class by name.
    ///
    /// # Example
    /// ```rust,ignore
    /// let class: JClass<'a> = env.find_class("java/lang/String");
    /// ```
    pub fn find_class<S>(&self, name: S) -> Result<JClass<'a>>
        where S: Into<JNIString>
    {
        let name = name.into();
        let class = jni_call!(self.internal, FindClass, name.as_ptr());
        Ok(class)
    }

    /// Get the superclass for a particular class. As with `find_class`, takes
    /// a descriptor.
    pub fn get_superclass<T>(&self, class: T) -> Result<JClass>
        where T: Desc<'a, JClass<'a>>
    {
        let class = class.lookup(self)?;
        Ok(jni_call!(self.internal, GetSuperclass, class.into_inner()))
    }

    /// Tests whether class1 is assignable from class2.
    pub fn is_assignable_from<T, U>(&self, class1: T, class2: U) -> Result<bool>
        where T: Desc<'a, JClass<'a>>,
              U: Desc<'a, JClass<'a>>
    {
        let class1 = class1.lookup(self)?;
        let class2 = class2.lookup(self)?;
        Ok(unsafe {
               jni_unchecked!(self.internal,
                              IsAssignableFrom,
                              class1.into_inner(),
                              class2.into_inner())
           } == sys::JNI_TRUE)
    }

    /// Raise an exception from an existing object. This will continue being
    /// thrown in java unless `exception_clear` is called.
    pub fn throw<E>(&self, obj: E) -> Result<()>
        where E: Desc<'a, JThrowable<'a>>
    {
        let throwable: JThrowable<'a> = obj.lookup(self)?;
        let res: i32 = unsafe { jni_unchecked!(self.internal, Throw, throwable.into_inner()) };
        if res < 0 {
            Err(format!("throw failed with code {}", res).into())
        } else {
            Ok(())
        }
    }

    /// Create and throw a new exception from a class descriptor and an error
    /// message.
    pub fn throw_new<S, T>(&self, class: T, msg: S) -> Result<()>
        where S: Into<JNIString>,
              T: Desc<'a, JClass<'a>>
    {
        let class = class.lookup(self)?;
        let msg = msg.into();
        let res: i32 =
            unsafe { jni_unchecked!(self.internal, ThrowNew, class.into_inner(), msg.as_ptr()) };
        if res < 0 {
            Err(format!("throw failed with code {}", res).into())
        } else {
            Ok(())
        }
    }

    /// Check whether or not an exception is currently in the process of being
    /// thrown. An exception is in this state from the time it gets thrown and
    /// not caught in a java function until `exception_clear` is called.
    pub fn exception_occurred(&self) -> Result<JThrowable> {
        let throwable = jni_call!(self.internal, ExceptionOccurred);
        Ok(throwable)
    }

    /// Print exception information to the console.
    pub fn exception_describe(&self) -> Result<()> {
        unsafe { jni_unchecked!(self.internal, ExceptionDescribe) };
        Ok(())
    }

    /// Clear an exception in the process of being thrown. If this is never
    /// called, the exception will continue being thrown when control is
    /// returned to java.
    pub fn exception_clear(&self) -> Result<()> {
        unsafe { jni_unchecked!(self.internal, ExceptionClear) };
        Ok(())
    }

    /// Abort the JVM with an error message.
    #[allow(unused_variables, unreachable_code)]
    pub fn fatal_error<S: Into<JNIString>>(&self, msg: S) -> ! {
        let msg = msg.into();
        let res: Result<()> =
            catch!({
                       unsafe { jni_unchecked!(self.internal, FatalError, msg.as_ptr()) }
                       unreachable!()
                   });

        panic!(res.unwrap_err());
    }

    /// Check to see if an exception is being thrown. This only differs from
    /// `exception_occurred` in that it doesn't return the actual thrown
    /// exception.
    pub fn exception_check(&self) -> Result<bool> {
        let check = unsafe { jni_unchecked!(self.internal, ExceptionCheck) } == sys::JNI_TRUE;
        Ok(check)
    }

    /// Turns an object into a global ref. This has the benefit of removing the
    /// lifetime bounds since it's guaranteed to not get GC'd by java. It
    /// releases the GC pin upon being dropped.
    pub fn new_global_ref(&self, obj: JObject) -> Result<GlobalRef> {
        non_null!(obj, "new_global_ref obj argument");
        let new_ref: JObject = jni_call!(self.internal, NewGlobalRef, obj.into_inner());
        let global = unsafe { GlobalRef::new(self.internal, new_ref.into_inner()) };
        Ok(global)
    }

    // Not public yet - not sure what the GC behavior is. Needs more research
    #[allow(dead_code)]
    fn new_local_ref(&self, obj: JObject) -> Result<JObject> {
        non_null!(obj, "new_local_ref obj argument");
        Ok(jni_call!(self.internal, NewLocalRef, obj.into_inner()))
    }

    #[allow(dead_code)]
    fn delete_local_ref(&self, obj: JObject) -> Result<()> {
        non_null!(obj, "delete_local_ref obj argument");
        Ok(unsafe {
               jni_unchecked!(self.internal, DeleteLocalRef, obj.into_inner());
               check_exception!(self.internal);
           })
    }

    /// Allocates a new object from a class descriptor without running a
    /// constructor.
    pub fn alloc_object<T>(&self, class: T) -> Result<JObject>
        where T: Desc<'a, JClass<'a>>
    {
        let class = class.lookup(self)?;
        Ok(jni_call!(self.internal, AllocObject, class.into_inner()))
    }

    /// Common functionality for finding methods.
    fn get_method_id_base<T, U, V, C, R>(&self,
                                         class: T,
                                         name: U,
                                         sig: V,
                                         get_method: C)
                                         -> Result<R>
        where T: Desc<'a, JClass<'a>>,
              U: Into<JNIString>,
              V: Into<JNIString>,
              C: Fn(&JClass<'a>, &JNIString, &JNIString) -> Result<R>
    {
        let class = class.lookup(self)?;
        let ffi_name = name.into();
        let sig = sig.into();

        let res: Result<R> = catch!({
                                        get_method(&class, &ffi_name, &sig)
                                    });

        match res {
            Ok(m) => Ok(m),
            Err(e) => {
                match e.kind() {
                    &ErrorKind::NullPtr(_) => {
                        let name: String = ffi_name.into();
                        let sig: String = sig.into();
                        return Err(ErrorKind::MethodNotFound(name, sig).into());
                    }
                    _ => return Err(e),
                }
            }
        }
    }

    /// Look up a method by class descriptor, name, and
    /// signature.
    ///
    /// # Example
    /// ```rust,ignore
    /// let method_id: JMethodID = env.get_method_id(
    ///     "java/lang/String", "substring", "(II)Ljava/lang/String;",
    /// );
    /// ```
    pub fn get_method_id<T, U, V>(&self, class: T, name: U, sig: V) -> Result<JMethodID<'a>>
        where T: Desc<'a, JClass<'a>>,
              U: Into<JNIString>,
              V: Into<JNIString>
    {
        self.get_method_id_base(class, name, sig, |class, name, sig| {
            Ok(jni_call!(self.internal,
                         GetMethodID,
                         class.into_inner(),
                         name.as_ptr(),
                         sig.as_ptr()))
        })
    }
    /// Look up a static method by class descriptor, name, and
    /// signature.
    ///
    /// # Example
    /// ```rust,ignore
    /// let method_id: JMethodID = env.get_static_method_id(
    ///     "java/lang/String", "valueOf", "(I)Ljava/lang/String;",
    /// );
    /// ```
    pub fn get_static_method_id<T, U, V>(&self,
                                         class: T,
                                         name: U,
                                         sig: V)
                                         -> Result<JStaticMethodID<'a>>
        where T: Desc<'a, JClass<'a>>,
              U: Into<JNIString>,
              V: Into<JNIString>
    {
        self.get_method_id_base(class, name, sig, |class, name, sig| {
            Ok(jni_call!(self.internal,
                         GetStaticMethodID,
                         class.into_inner(),
                         name.as_ptr(),
                         sig.as_ptr()))
        })
    }
    /// Look up the field ID for a class/name/type combination.
    ///
    /// # Example
    /// ```rust,ignore
    /// let field_id = env.get_field_id("com/my/Class", "intField", "I");
    /// ```
    pub fn get_field_id<T, U, V>(&self, class: T, name: U, sig: V) -> Result<JFieldID<'a>>
        where T: Desc<'a, JClass<'a>>,
              U: Into<JNIString>,
              V: Into<JNIString>
    {
        let class = class.lookup(self)?;
        let ffi_name = name.into();
        let ffi_sig = sig.into();

        let res: Result<JFieldID> = catch!({
                                               Ok(jni_call!(self.internal,
                                                            GetFieldID,
                                                            class.into_inner(),
                                                            ffi_name.as_ptr(),
                                                            ffi_sig.as_ptr()))
                                           });

        match res {
            Ok(m) => Ok(m),
            Err(e) => {
                match e.kind() {
                    &ErrorKind::NullPtr(_) => {
                        let name: String = ffi_name.into();
                        let sig: String = ffi_sig.into();
                        return Err(ErrorKind::FieldNotFound(name, sig).into());
                    }
                    _ => return Err(e),
                }
            }
        }
    }

    /// Get the class for an object.
    pub fn get_object_class(&self, obj: JObject) -> Result<JClass> {
        Ok(jni_call!(self.internal, GetObjectClass, obj.into_inner()))
    }

    /// Call a static method in an unsafe manner. This does nothing to check
    /// whether the method is valid to call on the class, whether the return
    /// type is correct, or whether the number of args is valid for the method.
    ///
    /// Under the hood, this simply calls the `CallStatic<Type>MethodA` method
    /// with the provided arguments.
    #[allow(unused_unsafe)]
    pub unsafe fn call_static_method_unsafe<T, U>(&self,
                                                  class: T,
                                                  method_id: U,
                                                  ret: JavaType,
                                                  args: &[JValue])
                                                  -> Result<JValue>
        where T: Desc<'a, JClass<'a>>,
              U: Desc<'a, JStaticMethodID<'a>>
    {
        let class = class.lookup(self)?;

        let method_id = method_id.lookup(self)?.into_inner();

        let class = class.into_inner();
        let args: Vec<jvalue> = args.into_iter().map(|v| v.to_jni()).collect();
        let jni_args = args.as_ptr();

        // TODO clean this up
        Ok(match ret {
               JavaType::Object(_) |
               JavaType::Array(_) => {
            let obj: JObject = jni_call!(self.internal,
                                         CallStaticObjectMethodA,
                                         class,
                                         method_id,
                                         jni_args);
            obj.into()
        } // JavaType::Object
               JavaType::Method(_) => unimplemented!(),
               JavaType::Primitive(p) => {
            let v: JValue = match p {
                Primitive::Boolean => {
                    (jni_unchecked!(self.internal,
                                    CallStaticBooleanMethodA,
                                    class,
                                    method_id,
                                    jni_args) == sys::JNI_TRUE)
                            .into()
                }
                Primitive::Char => {
                    jni_unchecked!(self.internal,
                                   CallStaticCharMethodA,
                                   class,
                                   method_id,
                                   jni_args)
                            .into()
                }
                Primitive::Short => {
                    jni_unchecked!(self.internal,
                                   CallStaticShortMethodA,
                                   class,
                                   method_id,
                                   jni_args)
                            .into()
                }
                Primitive::Int => {
                    jni_unchecked!(self.internal,
                                   CallStaticIntMethodA,
                                   class,
                                   method_id,
                                   jni_args)
                            .into()
                }
                Primitive::Long => {
                    jni_unchecked!(self.internal,
                                   CallStaticLongMethodA,
                                   class,
                                   method_id,
                                   jni_args)
                            .into()
                }
                Primitive::Float => {
                    jni_unchecked!(self.internal,
                                   CallStaticFloatMethodA,
                                   class,
                                   method_id,
                                   jni_args)
                            .into()
                }
                Primitive::Double => {
                    jni_unchecked!(self.internal,
                                   CallStaticDoubleMethodA,
                                   class,
                                   method_id,
                                   jni_args)
                            .into()
                }
                Primitive::Byte => {
                    jni_unchecked!(self.internal,
                                   CallStaticByteMethodA,
                                   class,
                                   method_id,
                                   jni_args)
                            .into()
                }
                Primitive::Void => {
                    jni_unchecked!(self.internal,
                                   CallStaticVoidMethodA,
                                   class,
                                   method_id,
                                   jni_args)
                            .into()
                }
            };
            v.into()
        } // JavaType::Primitive
           }) // match parsed.ret
    }

    /// Call an object method in an unsafe manner. This does nothing to check
    /// whether the method is valid to call on the object, whether the return
    /// type is correct, or whether the number of args is valid for the method.
    ///
    /// Under the hood, this simply calls the `Call<Type>MethodA` method with
    /// the provided arguments.
    #[allow(unused_unsafe)]
    pub unsafe fn call_method_unsafe<T>(&self,
                                        obj: JObject,
                                        method_id: T,
                                        ret: JavaType,
                                        args: &[JValue])
                                        -> Result<JValue>
        where T: Desc<'a, JMethodID<'a>>
    {
        let method_id = method_id.lookup(self)?.into_inner();

        let obj = obj.into_inner();

        let args: Vec<jvalue> = args.into_iter().map(|v| v.to_jni()).collect();
        let jni_args = args.as_ptr();

        // TODO clean this up
        Ok(match ret {
               JavaType::Object(_) |
               JavaType::Array(_) => {
            let obj: JObject =
                jni_call!(self.internal, CallObjectMethodA, obj, method_id, jni_args);
            obj.into()
        } // JavaType::Object
               JavaType::Method(_) => unimplemented!(),
               JavaType::Primitive(p) => {
            let v: JValue = match p {
                Primitive::Boolean => {
                    (jni_unchecked!(self.internal,
                                    CallBooleanMethodA,
                                    obj,
                                    method_id,
                                    jni_args) == sys::JNI_TRUE)
                            .into()
                }
                Primitive::Char => {
                    jni_unchecked!(self.internal, CallCharMethodA, obj, method_id, jni_args).into()
                }
                Primitive::Short => {
                    jni_unchecked!(self.internal, CallShortMethodA, obj, method_id, jni_args).into()
                }
                Primitive::Int => {
                    jni_unchecked!(self.internal, CallIntMethodA, obj, method_id, jni_args).into()
                }
                Primitive::Long => {
                    jni_unchecked!(self.internal, CallLongMethodA, obj, method_id, jni_args).into()
                }
                Primitive::Float => {
                    jni_unchecked!(self.internal, CallFloatMethodA, obj, method_id, jni_args).into()
                }
                Primitive::Double => {
                    jni_unchecked!(self.internal, CallDoubleMethodA, obj, method_id, jni_args)
                        .into()
                }
                Primitive::Byte => {
                    jni_unchecked!(self.internal, CallByteMethodA, obj, method_id, jni_args).into()
                }
                Primitive::Void => {
                    jni_unchecked!(self.internal, CallVoidMethodA, obj, method_id, jni_args);
                    return Ok(JValue::Void);
                }
            };
            v.into()
        } // JavaType::Primitive
           }) // match parsed.ret
    }

    /// Calls an object method safely. This comes with a number of
    /// lookups/checks. It
    ///
    /// * Parses the type signature to find the number of arguments and return
    ///   type
    /// * Looks up the JClass for the given object.
    /// * Looks up the JMethodID for the class/name/signature combination
    /// * Ensures that the number of args matches the signature
    /// * Calls `call_method_unsafe` with the verified safe arguments.
    ///
    /// Note: this may cause a java exception if the arguments are the wrong
    /// type, in addition to if the method itself throws.
    pub fn call_method<S, T>(&'a self,
                             obj: JObject,
                             name: S,
                             sig: T,
                             args: &[JValue])
                             -> Result<JValue>
        where S: Into<JNIString>,
              T: Into<JNIString> + AsRef<str>
    {
        non_null!(obj, "call_method obj argument");

        // parse the signature
        let parsed = TypeSignature::from_str(sig.as_ref())?;
        if parsed.args.len() != args.len() {
            return Err(ErrorKind::InvalidArgList.into());
        }

        let class = self.get_object_class(obj)?;

        unsafe { self.call_method_unsafe(obj, (class, name, sig), parsed.ret, args) }
    }

    /// Calls a static method safely. This comes with a number of
    /// lookups/checks. It
    ///
    /// * Parses the type signature to find the number of arguments and return
    ///   type
    /// * Looks up the JMethodID for the class/name/signature combination
    /// * Ensures that the number of args matches the signature
    /// * Calls `call_method_unsafe` with the verified safe arguments.
    ///
    /// Note: this may cause a java exception if the arguments are the wrong
    /// type, in addition to if the method itself throws.
    pub fn call_static_method<T, U, V>(&self,
                                       class: T,
                                       name: U,
                                       sig: V,
                                       args: &[JValue])
                                       -> Result<JValue>
        where T: Desc<'a, JClass<'a>>,
              U: Into<JNIString>,
              V: Into<JNIString> + AsRef<str>
    {
        let parsed = TypeSignature::from_str(&sig)?;
        if parsed.args.len() != args.len() {
            return Err(ErrorKind::InvalidArgList.into());
        }

        // go ahead and look up the class since it's already Copy,
        // and we'll need that for the next call.
        let class = class.lookup(self)?;

        unsafe { self.call_static_method_unsafe(class, (class, name, sig), parsed.ret, args) }
    }

    /// Create a new object using a constructor. This is done safely using
    /// checks similar to those in `call_static_method`.
    pub fn new_object<T, U>(&self,
                            class: T,
                            ctor_sig: U,
                            ctor_args: &[JValue])
                            -> Result<JObject<'a>>
        where T: Desc<'a, JClass<'a>>,
              U: Into<JNIString> + AsRef<str>
    {
        // parse the signature
        let parsed = TypeSignature::from_str(&ctor_sig)?;

        if parsed.args.len() != ctor_args.len() {
            return Err(ErrorKind::InvalidArgList.into());
        }

        if parsed.ret != JavaType::Primitive(Primitive::Void) {
            return Err(ErrorKind::InvalidCtorReturn.into());
        }

        let jni_args: Vec<jvalue> = ctor_args.into_iter().map(|v| v.to_jni()).collect();

        // build strings
        let name = "<init>";

        let class = class.lookup(self)?;

        let method_id: JMethodID = (class, name, ctor_sig).lookup(self)?;

        let jni_args = jni_args.as_ptr();

        Ok(jni_call!(self.internal,
                     NewObjectA,
                     class.into_inner(),
                     method_id.into_inner(),
                     jni_args))
    }

    /// Cast a JObject to a JMap. This won't throw exceptions or return errors
    /// in the event that the object isn't actually a map, but the methods on
    /// the resulting map object will.
    pub fn get_map(&self, obj: JObject<'a>) -> Result<JMap> {
        non_null!(obj, "get_map obj argument");
        JMap::from_env(self, obj)
    }

    /// Get a JavaStr from a JString. This allows conversions from java string
    /// objects to rust strings.
    ///
    /// This entails a call to `GetStringUTFChars` and only decodes java's
    /// modified UTF-8 format on conversion to a rust-compatible string.
    pub fn get_string(&self, obj: JString<'a>) -> Result<JavaStr> {
        non_null!(obj, "get_string obj argument");
        JavaStr::from_env(self, obj)
    }

    /// Get a pointer to the character array beneath a JString. This is in
    /// Java's modified UTF-8 and will leak memory if `release_string_utf_chars`
    /// is never called.
    #[allow(unused_unsafe)]
    pub unsafe fn get_string_utf_chars(&self, obj: JString) -> Result<*const c_char> {
        non_null!(obj, "get_string_utf_chars obj argument");
        let ptr: *const c_char = jni_call!(self.internal,
                                           GetStringUTFChars,
                                           obj.into_inner(),
                                           ::std::ptr::null::<jboolean>() as *mut jboolean);
        Ok(ptr)
    }

    /// Unpin the array returned by `get_string_utf_chars`.
    #[allow(unused_unsafe)]
    pub unsafe fn release_string_utf_chars(&self, obj: JString, arr: *const c_char) -> Result<()> {
        non_null!(obj, "release_string_utf_chars obj argument");
        jni_unchecked!(self.internal, ReleaseStringUTFChars, obj.into_inner(), arr);
        check_exception!(self.internal);
        Ok(())
    }

    /// Create a new java string object from a rust string. This requires a
    /// re-encoding of rusts *real* UTF-8 strings to java's modified UTF-8
    /// format.
    pub fn new_string<S: Into<JNIString>>(&self, from: S) -> Result<JString<'a>> {
        let ffi_str = from.into();
        Ok(jni_call!(self.internal, NewStringUTF, ffi_str.as_ptr()))
    }

    /// Create a new java byte array from a rust byte slice.
    pub fn new_byte_array(&self, buf: &[i8]) -> Result<jbyteArray> {
        let length = buf.len() as i32;
        let bytes: jbyteArray = jni_call!(self.internal, NewByteArray, length);
        unsafe {
            jni_unchecked!(self.internal, SetByteArrayRegion, bytes, 0, length, buf.as_ptr());
        }
        Ok(bytes)
    }

    /// Get a field without checking the provided type against the actual field.
    #[allow(unused_unsafe)]
    pub unsafe fn get_field_unsafe<T>(&self, obj: JObject, field: T, ty: JavaType) -> Result<JValue>
        where T: Desc<'a, JFieldID<'a>>
    {
        non_null!(obj, "get_field_typed obj argument");

        let field = field.lookup(self)?.into_inner();
        let obj = obj.into_inner();

        // TODO clean this up
        Ok(match ty {
               JavaType::Object(_) |
               JavaType::Array(_) => {
            let obj: JObject = jni_call!(self.internal, GetObjectField, obj, field);
            obj.into()
        } // JavaType::Object
               JavaType::Method(_) => unimplemented!(),
               JavaType::Primitive(p) => {
            let v: JValue = match p {
                Primitive::Boolean => {
                    (jni_unchecked!(self.internal, GetBooleanField, obj, field) == sys::JNI_TRUE)
                        .into()
                }
                Primitive::Char => jni_unchecked!(self.internal, GetCharField, obj, field).into(),
                Primitive::Short => jni_unchecked!(self.internal, GetShortField, obj, field).into(),
                Primitive::Int => jni_unchecked!(self.internal, GetIntField, obj, field).into(),
                Primitive::Long => jni_unchecked!(self.internal, GetLongField, obj, field).into(),
                Primitive::Float => jni_unchecked!(self.internal, GetFloatField, obj, field).into(),
                Primitive::Double => {
                    jni_unchecked!(self.internal, GetDoubleField, obj, field).into()
                }
                Primitive::Byte => jni_unchecked!(self.internal, GetByteField, obj, field).into(),
                Primitive::Void => {
                    return Err(ErrorKind::WrongJValueType("void", "see java field").into());
                }
            };
            v.into()
        } // JavaType::Primitive
           }) // match parsed.ret
    }

    /// Set a field without any type checking.
    pub unsafe fn set_field_unsafe<T>(&self, obj: JObject, field: T, val: JValue) -> Result<()>
        where T: Desc<'a, JFieldID<'a>>
    {
        non_null!(obj, "set_field_typed obj argument");

        let field = field.lookup(self)?.into_inner();
        let obj = obj.into_inner();

        // TODO clean this up
        match val {
            JValue::Object(o) => {
                jni_unchecked!(self.internal, SetObjectField, obj, field, o.into_inner());
            } // JavaType::Object
            JValue::Bool(b) => {
                jni_unchecked!(self.internal, SetBooleanField, obj, field, b);
            }
            JValue::Char(c) => {
                jni_unchecked!(self.internal, SetCharField, obj, field, c);
            }
            JValue::Short(s) => {
                jni_unchecked!(self.internal, SetShortField, obj, field, s);
            }
            JValue::Int(i) => {
                jni_unchecked!(self.internal, SetIntField, obj, field, i);
            }
            JValue::Long(l) => {
                jni_unchecked!(self.internal, SetLongField, obj, field, l);
            }
            JValue::Float(f) => {
                jni_unchecked!(self.internal, SetFloatField, obj, field, f);
            }
            JValue::Double(d) => {
                jni_unchecked!(self.internal, SetDoubleField, obj, field, d);
            }
            JValue::Byte(b) => {
                jni_unchecked!(self.internal, SetByteField, obj, field, b);
            }
            JValue::Void => {
                return Err(ErrorKind::WrongJValueType("void", "see java field").into());
            }
        };

        Ok(())
    }

    /// Get a field. Requires an object class lookup and a field id lookup
    /// internally.
    pub fn get_field<S, T>(&self, obj: JObject, name: S, ty: T) -> Result<JValue>
        where S: Into<JNIString>,
              T: Into<JNIString> + AsRef<str>
    {
        let class: JClass = self.get_object_class(obj)?;

        let parsed = JavaType::from_str(ty.as_ref())?;

        let field_id: JFieldID = (class, name, ty).lookup(self)?;

        unsafe { self.get_field_unsafe(obj, field_id, parsed) }
    }

    /// Set a field. Does the same lookups as `get_field` and ensures that the
    /// type matches the given value.
    pub fn set_field<S, T>(&self, obj: JObject, name: S, ty: T, val: JValue) -> Result<()>
        where S: Into<JNIString>,
              T: Into<JNIString> + AsRef<str>
    {
        let parsed = JavaType::from_str(ty.as_ref())?;
        let in_type = val.primitive_type();

        match parsed {
            JavaType::Object(_) |
            JavaType::Array(_) => {
                if let None = in_type {
                    // we're good here
                } else {
                    return Err(ErrorKind::WrongJValueType(val.type_name(), "see java field")
                                   .into());
                }
            }
            JavaType::Primitive(p) => {
                if let Some(in_p) = in_type {
                    if in_p == p {
                        // good
                    } else {
                        return Err(ErrorKind::WrongJValueType(val.type_name(), "see java field")
                                       .into());
                    }
                } else {
                    return Err(ErrorKind::WrongJValueType(val.type_name(), "see java field")
                                   .into());
                }
            }
            JavaType::Method(_) => unimplemented!(),
        }

        let class = self.get_object_class(obj)?;

        unsafe { self.set_field_unsafe(obj, (class, name, ty), val) }
    }

    /// Surrenders ownership of a rust object to Java. Requires an object with a
    /// `long` field to store the pointer. The Rust value will be wrapped in a
    /// Mutex since Java will be controlling where it'll be used thread-wise.
    /// Unsafe because it leaks memory if `take_rust_field` is never called (so
    /// be sure to make a finalizer).
    ///
    /// **DO NOT** make a copy of the object containing one of these fields. If
    /// you've set up a finalizer to pass it back to Rust upon being GC'd, it
    /// will point to invalid memory and will likely attempt to be deallocated
    /// again.
    #[allow(unused_variables)]
    pub unsafe fn set_rust_field<S, T>(&self, obj: JObject, field: S, rust_object: T) -> Result<()>
        where S: AsRef<str>,
              T: Send + 'static
    {
        let class = self.get_object_class(obj)?;
        let field_id: JFieldID = (class, &field, "J").lookup(self)?;

        let guard = self.lock_obj(obj)?;

        // Check to see if we've already set this value. If it's not null, that
        // means that we're going to leak memory if it gets overwritten.
        let field_ptr =
            self.get_field_unsafe(obj, field_id, JavaType::Primitive(Primitive::Long))?
                .j()? as *mut Mutex<T>;
        if !field_ptr.is_null() {
            return Err(format!("field already set: {}", field.as_ref()).into());
        }

        let mbox = Box::new(::std::sync::Mutex::new(rust_object));
        let ptr: *mut Mutex<T> = Box::into_raw(mbox);

        self.set_field_unsafe(obj, field_id, (ptr as ::sys::jlong).into())
    }

    /// Gets a lock on a Rust value that's been given to a Java object. Java
    /// still retains ownership and `take_rust_field` will still need to be
    /// called at some point. Checks for a null pointer, but assumes that the
    /// data it ponts to is valid for T.
    #[allow(unused_variables)]
    pub unsafe fn get_rust_field<S, T>(&self, obj: JObject, field: S) -> Result<MutexGuard<T>>
        where S: Into<JNIString>,
              T: Send + 'static
    {
        let guard = self.lock_obj(obj)?;

        let ptr = self.get_field(obj, field, "J")?
            .j()? as *mut Mutex<T>;
        non_null!(ptr, "rust value from Java");
        Ok((*ptr).lock().unwrap())
    }

    /// Take a Rust field back from Java. Makes sure that the pointer is
    /// non-null, but still assumes that the data it points to is valid for T.
    /// Sets the field to a null pointer to signal that it's empty.
    ///
    /// This will return an error in the event that there's an outstanding lock
    /// on the object.
    #[allow(unused_variables)]
    pub unsafe fn take_rust_field<S, T>(&self, obj: JObject, field: S) -> Result<T>
        where S: AsRef<str>,
              T: Send + 'static
    {
        let class = self.get_object_class(obj)?;
        let field_id: JFieldID = (class, &field, "J").lookup(self)?;

        let mbox = {
            let guard = self.lock_obj(obj)?;

            let ptr =
                self.get_field_unsafe(obj, field_id, JavaType::Primitive(Primitive::Long))?
                    .j()? as *mut Mutex<T>;

            non_null!(ptr, "rust value from Java");

            let mbox = Box::from_raw(ptr);

            // attempt to acquire the lock. This prevents us from consuming the
            // mutex if there's an outstanding lock. No one else will be able to
            // get a new one as long as we're in the guarded scope.
            let _ = mbox.try_lock()?;

            self.set_field_unsafe(obj,
                                  field_id,
                                  (::std::ptr::null_mut::<()>() as sys::jlong).into())?;

            mbox
        };

        Ok(mbox.into_inner().unwrap())
    }

    /// Lock a Java object. The MonitorGuard that this returns is responsible
    /// for ensuring that it gets unlocked.
    pub fn lock_obj(&self, obj: JObject) -> Result<MonitorGuard<'a>> {
        unsafe {
            let _ = jni_unchecked!(self.internal, MonitorEnter, obj.into_inner());
        }

        Ok(MonitorGuard {
               obj: obj.into_inner(),
               env: self.internal,
               life: Default::default(),
           })
    }
}

/// Guard for a lock on a java object. This gets returned from the `lock_obj`
/// method.
pub struct MonitorGuard<'a> {
    obj: sys::jobject,
    env: *mut sys::JNIEnv,
    life: PhantomData<&'a ()>,
}

impl<'a> Drop for MonitorGuard<'a> {
    fn drop(&mut self) {
        let res: Result<()> = catch!({
                                         unsafe { jni_unchecked!(self.env, MonitorExit, self.obj) };
                                         Ok(())
                                     });

        match res {
            Err(e) => warn!("error releasing java monitor: {}", e),
            _ => {}
        }
    }
}