-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathjava_env_wrapper.rs
More file actions
1519 lines (1373 loc) · 46.6 KB
/
java_env_wrapper.rs
File metadata and controls
1519 lines (1373 loc) · 46.6 KB
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
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::java::java_error::JavaError;
use crate::java::java_field::{
JavaBooleanField, JavaByteField, JavaCharField, JavaDoubleField, JavaField, JavaFloatField,
JavaIntField, JavaLongField, JavaObjectField, JavaShortField, StaticJavaBooleanField,
StaticJavaByteField, StaticJavaCharField, StaticJavaDoubleField, StaticJavaFloatField,
StaticJavaIntField, StaticJavaLongField, StaticJavaObjectField, StaticJavaShortField,
};
use crate::java::java_type::JavaType;
use crate::java::java_vm::JavaVM;
use crate::java::jni_error::JNIError;
use crate::java::objects::args::JavaArgs;
use crate::java::objects::array::{
JavaArray, JavaBooleanArray, JavaByteArray, JavaCharArray, JavaDoubleArray, JavaFloatArray,
JavaIntArray, JavaLongArray, JavaObjectArray, JavaShortArray,
};
use crate::java::objects::class::{GlobalJavaClass, JavaClass};
use crate::java::objects::constructor::JavaConstructor;
use crate::java::objects::java_object::JavaObject;
use crate::java::objects::method::{JavaMethod, JavaObjectMethod};
use crate::java::objects::object::{GlobalJavaObject, LocalJavaObject};
use crate::java::objects::string::JavaString;
use crate::java::objects::value::JavaBoolean;
use crate::java::traits::GetRaw;
use crate::java::util::helpers::{jni_error_to_string, ResultType};
use crate::java::vm_ptr::JavaVMPtr;
use crate::objects::args::AsJavaArg;
#[cfg(feature = "type_check")]
use crate::signature::Signature;
#[cfg(feature = "type_check")]
use crate::traits::GetSignature;
use crate::traits::GetSignatureRef;
use crate::{
assert_non_null, define_array_methods, define_call_methods, define_field_methods, sys,
};
use std::borrow::Borrow;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fmt::Display;
use std::ops::Not;
use std::ptr;
use std::sync::{Arc, Mutex};
use std::thread::ThreadId;
/// A wrapper around a JNIEnv.
/// This manages the reference count for the current thread
/// and provides convenience methods to the jvm.
/// Rather than copying or creating this directly, attach a new
/// thread using [`JavaVM::attach_thread`](JavaVM::attach_thread).
pub struct JavaEnvWrapper<'a> {
pub jvm: Option<Arc<Mutex<JavaVMPtr>>>,
pub env: *mut sys::JNIEnv,
pub methods: sys::JNINativeInterface_,
thread_id: ThreadId,
_marker: std::marker::PhantomData<&'a *mut sys::JNIEnv>,
}
impl<'a> JavaEnvWrapper<'a> {
/// You should probably not use this.
pub(crate) fn new(jvm: Arc<Mutex<JavaVMPtr>>, env: *mut sys::JNIEnv) -> Self {
#[cfg(feature = "log")]
crate::trace!(
"Creating JavaEnv in thread {:?}",
std::thread::current().id()
);
assert_non_null!(env, "JavaEnvWrapper::new: env is null");
Self {
jvm: Some(jvm),
env,
methods: unsafe { *(*env) },
thread_id: std::thread::current().id(),
_marker: std::marker::PhantomData,
}
}
pub unsafe fn from_raw(env: *mut sys::JNIEnv) -> Self {
assert_non_null!(env, "JavaEnvWrapper::from_raw: env is null");
let mut res = Self {
jvm: None,
env,
methods: *(*env),
thread_id: std::thread::current().id(),
_marker: std::marker::PhantomData,
};
res.jvm = res.load_java_vm().ok();
res
}
fn load_java_vm(&self) -> ResultType<Arc<Mutex<JavaVMPtr>>> {
let mut vm: *mut sys::JavaVM = ptr::null_mut();
let res =
unsafe { self.methods.GetJavaVM.unwrap()(self.env, &mut vm as *mut *mut sys::JavaVM) };
if res != sys::JNI_OK as _ || vm.is_null() {
Err(format!("Failed to get JavaVM: {}", jni_error_to_string(res)).into())
} else {
Ok(Arc::new(Mutex::new(JavaVMPtr::from_raw(vm))))
}
}
pub fn get_object_class(&'a self, object: JavaObject) -> ResultType<JavaClass<'a>> {
let class = unsafe { self.methods.GetObjectClass.unwrap()(self.env, object.get_raw()) };
if self.is_err() || class.is_null() {
Err(self.get_last_error(file!(), line!(), true, "GetObjectClass failed")?)
} else {
Ok(JavaClass::new(
class,
self,
#[cfg(feature = "type_check")]
object.get_signature().clone(),
))
}
}
pub fn get_object_signature(&self, object: JavaObject) -> ResultType<JavaType> {
let object_class = self.get_object_class(object.copy_ref())?;
let get_class = object_class.get_object_method("getClass", "()Ljava/lang/Class;")?;
let class = get_class
.call(object, &[])?
.ok_or("Object.getClass() returned null".to_string())?;
let java_class = self.get_java_lang_class()?;
let get_name = java_class.get_object_method("getName", "()Ljava/lang/String;")?;
let java_name = get_name
.call(JavaObject::from(class), &[])?
.ok_or("Class.getName() returned null".to_string())?;
// As JavaString::try_from calls get_object_signature in order
// to check if the passed type is a string, we need to get the
// string manually in order to prevent a stack overflow.
let name = unsafe { self.get_string_utf_chars(java_name.get_raw())? };
Ok(JavaType::new(name, true))
}
pub fn get_class_name(&self, object: JavaObject) -> ResultType<String> {
let object_class = self.get_object_class(object.copy_ref())?;
let get_class = object_class.get_object_method("getClass", "()Ljava/lang/Class;")?;
let class = get_class
.call(object, &[])?
.ok_or("Object.getClass() returned null".to_string())?;
let java_class = self.get_java_lang_class()?;
let get_name = java_class.get_object_method("getName", "()Ljava/lang/String;")?;
let java_name = get_name
.call(JavaObject::from(class), &[])?
.ok_or("Class.getName() returned null".to_string())?;
let str = JavaString::try_from(java_name)?;
str.to_string()
}
pub fn is_instance_of(&self, object: JavaObject, classname: &str) -> ResultType<bool> {
let class = self.find_class(classname, true)?;
let result = unsafe {
self.methods.IsInstanceOf.unwrap()(self.env, object.get_raw(), class.class())
};
if self.is_err() {
Err(self.get_last_error(file!(), line!(), true, "IsInstanceOf failed")?)
} else {
Ok(result != 0)
}
}
pub fn instance_of(&self, this: JavaObject, other: GlobalJavaClass) -> ResultType<bool> {
let result =
unsafe { self.methods.IsInstanceOf.unwrap()(self.env, this.get_raw(), other.class()) };
if self.is_err() {
Err(self.get_last_error(file!(), line!(), true, "IsInstanceOf failed")?)
} else {
Ok(result != 0)
}
}
pub fn throw_error(&self, message: String) {
let message = CString::new(message).unwrap();
unsafe {
self.methods.ThrowNew.unwrap()(
self.env,
self.find_class("java/lang/Exception", true)
.unwrap()
.class(),
message.as_ptr(),
);
}
}
pub fn throw(&self, object: JavaObject) {
unsafe {
self.methods.Throw.unwrap()(self.env, object.get_raw());
}
}
/// Check if an error has been thrown inside this environment
///
/// See also [`get_last_error`](Self::get_last_error).
fn is_err(&self) -> bool {
unsafe { self.methods.ExceptionCheck.unwrap()(self.env) != 0 }
}
/// Clear the (last) pending exception from this environment.
///
/// See also [`get_last_error`](Self::get_last_error).
fn clear_err(&self) {
unsafe {
self.methods.ExceptionClear.unwrap()(self.env);
}
}
/// Get the pending exception from this environment.
/// If no exception is pending, returns an error.
///
/// See also [`get_last_error`](Self::get_last_error).
fn exception_occurred(&'a self) -> ResultType<LocalJavaObject<'a>> {
let throwable = unsafe { self.methods.ExceptionOccurred.unwrap()(self.env) };
self.clear_err();
if throwable.is_null() {
Err(JNIError::from("Call to ExceptionOccurred failed").into())
} else {
Ok(LocalJavaObject::new(
throwable,
self,
#[cfg(feature = "type_check")]
JavaType::object(),
))
}
}
/// Convert the frames of the last pending exception to a rust error.
///
/// See [`get_last_error`](Self::get_last_error) which uses this method.
#[allow(clippy::too_many_arguments, clippy::only_used_in_recursion)]
fn convert_frames(
&self,
frames: &mut JavaObjectArray<'_>,
num_frames: i32,
throwable: JavaObject,
throwable_to_string: &JavaObjectMethod,
throwable_get_cause: &JavaObjectMethod,
throwable_get_stack_trace: &JavaObjectMethod,
stack_trace_element_to_string: &JavaObjectMethod,
causes: &mut Vec<String>,
stack_frames: &mut Vec<String>,
) -> ResultType<()> {
let throwable_string = throwable_to_string
.call_with_errors(throwable.copy_ref(), &[], false)?
.ok_or("Throwable.toString() returned null".to_string())?;
causes.push(throwable_string.to_java_string()?.try_into()?);
for i in 0..num_frames {
let frame = frames
.get_with_errors(i, false)?
.ok_or("A stack frame was null".to_string())?;
let frame_string = stack_trace_element_to_string
.call_with_errors(JavaObject::from(&frame), &[], false)?
.ok_or("StackTraceElement.toString() returned null".to_string())?;
stack_frames.push(frame_string.to_java_string()?.try_into()?);
}
let throwable = throwable_get_cause.call_with_errors(throwable, &[], false)?;
let throwable = if let Some(throwable) = throwable {
JavaObject::from(throwable)
} else {
return Ok(());
};
let frames_obj =
throwable_get_stack_trace.call_with_errors(throwable.copy_ref(), &[], false)?;
let mut frames = if let Some(f) = frames_obj {
JavaObjectArray::from(f)
} else {
return Ok(());
};
let num_frames = frames.len()?;
self.convert_frames(
&mut frames,
num_frames,
throwable.copy_ref(),
throwable_to_string,
throwable_get_cause,
throwable_get_stack_trace,
stack_trace_element_to_string,
causes,
stack_frames,
)
}
/// Get the last java error as an rust error.
/// If no error is pending, returns an error.
/// Clears the pending exception, converts the stack frames
/// and returns the error as an [`JavaError`](JavaError).
/// If this returns `Err`, an error occurred while converting the stack frames,
/// if this returns `Ok`, everything was converted correctly.
///
/// # Parameters
/// - `file` - The (source) file the error occurred in.
/// - `line` - The line the error occurred on.
/// - `convert_errors` - For internal use only, just pass `true`.
/// - `alt_text` - An alternative text to use when `convert_errors` is `false`.
fn get_last_error(
&self,
file: &str,
line: u32,
convert_errors: bool,
alt_text: &str,
) -> ResultType<Box<dyn Error + Send + Sync>> {
if !self.is_err() {
return Err(JNIError::from("No error occurred").into());
}
let mut own_stack_frames = vec![
format!("{}:{}", file, line).to_string(),
format!("{}:{}", file!(), line!()).to_string(),
];
let mut stack_frames: Vec<String> = Vec::new();
if !convert_errors {
self.clear_err();
return Err(JavaError::new(vec![], own_stack_frames, alt_text.to_string()).into());
}
let throwable: GlobalJavaObject = self.exception_occurred()?.try_into()?;
let throwable_class = self.find_class("java/lang/Throwable", false)?;
let throwable_get_cause = throwable_class.get_object_method_with_errors(
"getCause",
"()Ljava/lang/Throwable;",
false,
)?;
let throwable_get_stack_trace = throwable_class.get_object_method_with_errors(
"getStackTrace",
"()[Ljava/lang/StackTraceElement;",
false,
)?;
let throwable_to_string = throwable_class.get_object_method_with_errors(
"toString",
"()Ljava/lang/String;",
false,
)?;
let stack_trace_element_class = self.find_class("java/lang/StackTraceElement", false)?;
let stack_trace_element_to_string = stack_trace_element_class
.get_object_method_with_errors("toString", "()Ljava/lang/String;", false)?;
let mut frames = JavaObjectArray::from(
throwable_get_stack_trace
.call_with_errors(JavaObject::from(&throwable), &[], false)?
.ok_or("Throwable.getStackTrace() returned null".to_string())?,
);
let num_frames = frames.len()?;
let mut causes: Vec<String> = vec![];
self.convert_frames(
&mut frames,
num_frames,
JavaObject::from(&throwable),
&throwable_to_string,
&throwable_get_cause,
&throwable_get_stack_trace,
&stack_trace_element_to_string,
&mut causes,
&mut stack_frames,
)?;
stack_frames.append(&mut own_stack_frames);
Ok(
JavaError::new_with_throwable(causes, stack_frames, alt_text.to_string(), throwable)
.into(),
)
}
/// Delete the local reference of an java object.
/// Make sure to only call this once as any subsequent
/// calls will cause the program to segfault.
/// This is not strictly required by the jvm but should be done
/// for jni calls to the jvm. Do not call this if the object
/// has been converted to a global reference.
pub fn delete_local_ref(&self, object: sys::jobject) {
assert_non_null!(object);
unsafe {
self.methods.DeleteLocalRef.unwrap()(self.env, object);
}
}
/// Create a new global reference to a java object.
///
/// Used by [`GlobalJavaObject`](crate::java::java_object::GlobalJavaObject)
/// to create a global references from local ones.
pub fn new_global_object(
&self,
object: sys::jobject,
#[cfg(feature = "type_check")] signature: JavaType,
) -> ResultType<GlobalJavaObject> {
#[cfg(feature = "type_check")]
crate::trace!("Creating global reference to object of type {}", signature);
assert_non_null!(object);
let obj = unsafe { self.methods.NewGlobalRef.unwrap()(self.env, object) };
if self.is_err() || obj.is_null() {
self.clear_err();
Err(JNIError::new("Failed to create global reference".to_string()).into())
} else {
Ok(GlobalJavaObject::new(
obj,
self.jvm
.as_ref()
.ok_or("The jvm was unset".to_string())?
.clone(),
#[cfg(feature = "type_check")]
signature,
))
}
}
/// Find a class by its jni class name.
///
/// Used by [`JavaEnv.find_class()`](crate::java::java_env::JavaEnv::find_class)
/// and [`JavaClass.by_name()`](crate::java::java_object::JavaClass::by_name).
pub fn find_class(
&'a self,
class_name: &str,
resolve_errors: bool,
) -> ResultType<JavaClass<'a>> {
crate::trace!("Resolving class '{}'", class_name);
let c_class_name = CString::new(class_name)?;
let class = unsafe { self.methods.FindClass.unwrap()(self.env, c_class_name.as_ptr()) };
if self.is_err() || class.is_null() {
Err(self.get_last_error(
file!(),
line!(),
resolve_errors,
format!("Could not find class '{}'", class_name).as_str(),
)?)
} else {
Ok(JavaClass::new(
class,
self,
#[cfg(feature = "type_check")]
JavaType::new(class_name.to_string(), true),
))
}
}
/// Get `java.lang.Class`
pub fn get_java_lang_class(&'a self) -> ResultType<JavaClass<'a>> {
crate::trace!("Getting java.lang.Class");
self.find_class("java/lang/Class", true)
}
pub fn find_class_by_java_name(&'a self, class_name: String) -> ResultType<JavaClass<'a>> {
crate::trace!("Resolving class '{}'", class_name);
let class = self.get_java_lang_class()?;
let for_name = class.get_static_object_method(
"forName",
"(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;",
)?;
let java_class_name = JavaString::_try_from(class_name.clone(), self)?;
let arg = JavaBoolean::new(true);
let loader = self
.jvm
.as_ref()
.ok_or("The jvm was unset".to_string())?
.lock()
.map_err(|_| "Could not lock mutex".to_string())?
.class_loader()
.clone()
.unwrap();
let class_loader = LocalJavaObject::from_internal(loader.borrow(), self);
let res = for_name
.call(&[
java_class_name.as_arg(),
arg.as_arg(),
class_loader.as_arg(),
])?
.ok_or("Class.forName() returned null".to_string())?;
Ok(JavaClass::from_local(
res.assign_env(self),
#[cfg(feature = "type_check")]
JavaType::new(class_name, true),
))
}
/// Find a class by its java class name
///
/// Used by [`JavaEnv.find_class_by_java_name()`](crate::java::java_env::JavaEnv::find_class_by_java_name)
/// and [`GlobalJavaClass.by_name()`](crate::java::java_object::GlobalJavaClass::by_name).
pub fn find_global_class_by_java_name(
&'a self,
class_name: String,
) -> ResultType<GlobalJavaClass> {
crate::trace!("Resolving class '{}'", class_name);
let class = self.get_java_lang_class()?;
let for_name = class.get_static_object_method(
"forName",
"(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;",
)?;
let java_class_name = JavaString::_try_from(class_name.clone(), self)?;
let arg = JavaBoolean::new(true);
let loader = self
.jvm
.as_ref()
.ok_or("The jvm was unset".to_string())?
.lock()
.map_err(|_| "Could not lock mutex".to_string())?
.class_loader()
.clone()
.unwrap();
let class_loader = LocalJavaObject::from_internal(loader.borrow(), self);
let cls = GlobalJavaClass::try_from_local(
for_name
.call(&[
java_class_name.as_arg(),
arg.as_arg(),
class_loader.as_arg(),
])?
.ok_or("Class.forName() returned null".to_string())?,
#[cfg(feature = "type_check")]
JavaType::new(class_name, true),
)?;
Ok(cls)
}
pub fn get_system_class_loader(&self) -> ResultType<GlobalJavaObject> {
let class = self.find_class("java/lang/ClassLoader", true)?;
let get_system_class_loader =
class.get_static_object_method("getSystemClassLoader", "()Ljava/lang/ClassLoader;")?;
let loader = get_system_class_loader
.call(&[])?
.ok_or("ClassLoader.getSystemClassLoader() returned null".to_string())?;
GlobalJavaObject::try_from(loader)
}
pub fn get_method_id(
&self,
class: &'a JavaClass<'a>,
method_name: &str,
signature: &str,
) -> ResultType<JavaMethod<'a>> {
self.get_method_id_with_errors(class, method_name, signature, true)
}
pub fn get_method_id_with_errors(
&self,
class: &'a JavaClass<'a>,
method_name: &str,
signature: &str,
resolve_errors: bool,
) -> ResultType<JavaMethod<'a>> {
crate::trace!("Getting method id for {}{}", method_name, signature);
let method_name_str = CString::new(method_name)?;
let signature_str = CString::new(signature)?;
let method = unsafe {
self.methods.GetMethodID.unwrap()(
self.env,
class.class(),
method_name_str.as_ptr(),
signature_str.as_ptr(),
)
};
if self.is_err() || method.is_null() {
Err(self.get_last_error(
file!(),
line!(),
resolve_errors,
format!("Could not find method '{}{}'", method_name, signature).as_str(),
)?)
} else {
Ok(JavaMethod::new(
method,
class,
JavaType::from_method_return_type(signature)?,
false,
#[cfg(feature = "type_check")]
Signature::from_jni(signature)?,
#[cfg(feature = "type_check")]
method_name.to_string(),
))
}
}
pub fn get_static_method_id(
&self,
class: &'a JavaClass<'a>,
method_name: &str,
signature: &str,
) -> ResultType<JavaMethod<'a>> {
crate::trace!("Getting static method id for {}{}", method_name, signature);
let method_name_str = CString::new(method_name)?;
let signature_str = CString::new(signature)?;
let method = unsafe {
self.methods.GetStaticMethodID.unwrap()(
self.env,
class.class(),
method_name_str.as_ptr(),
signature_str.as_ptr(),
)
};
if self.is_err() || method.is_null() {
Err(self.get_last_error(
file!(),
line!(),
true,
format!("Could not find method '{}'", method_name).as_str(),
)?)
} else {
Ok(JavaMethod::new(
method,
class,
JavaType::from_method_return_type(signature)?,
true,
#[cfg(feature = "type_check")]
Signature::from_jni(signature)?,
#[cfg(feature = "type_check")]
method_name.to_string(),
))
}
}
unsafe fn convert_args(
&self,
args: JavaArgs,
#[cfg(feature = "type_check")] signature: &Signature,
) -> ResultType<Vec<sys::jvalue>> {
#[cfg(feature = "type_check")]
if !signature.matches(&args) {
Err(format!(
"The arguments do not match the method signature: ({}) != {}",
args.iter()
.map(|a| a.get_type().to_string())
.collect::<Vec<String>>()
.join(", "),
signature
)
.into())
} else {
Ok(args.iter().map(|arg| arg.to_java_value().value()).collect())
}
#[cfg(not(feature = "type_check"))]
Ok(args.iter().map(|arg| arg.to_java_value().value()).collect())
}
pub fn call_object_method(
&'a self,
object: JavaObject<'_>,
method: &JavaMethod<'_>,
args: JavaArgs,
) -> ResultType<Option<LocalJavaObject<'a>>> {
self.call_object_method_with_errors(object, method, args, true)
}
fn return_method_object(
&'a self,
obj: sys::jobject,
_method: &JavaMethod<'_>,
) -> ResultType<Option<LocalJavaObject<'a>>> {
Ok(obj.is_null().not().then(|| {
LocalJavaObject::new(
obj,
self,
#[cfg(feature = "type_check")]
_method.get_signature().get_return_type().clone(),
)
}))
}
pub fn call_object_method_with_errors(
&'a self,
object: JavaObject<'_>,
method: &JavaMethod<'_>,
args: JavaArgs<'_>,
resolve_errors: bool,
) -> ResultType<Option<LocalJavaObject<'a>>> {
#[cfg(feature = "log")]
crate::trace!(
"Calling object method {} with {} args",
method.get_java_signature(),
args.len()
);
let obj = unsafe {
let args = self.convert_args(
args,
#[cfg(feature = "type_check")]
method.get_signature(),
)?;
self.methods.CallObjectMethodA.unwrap()(
self.env,
object.get_raw(),
method.id(),
args.as_ptr(),
)
};
if self.is_err() {
#[cfg(feature = "log")]
log::debug!("Method {} threw an error", method.get_java_signature());
Err(self.get_last_error(
file!(),
line!(),
resolve_errors,
"CallObjectMethodA failed",
)?)
} else {
self.return_method_object(obj, method)
}
}
pub fn call_static_object_method(
&'a self,
class: &JavaClass<'_>,
method: &JavaMethod<'_>,
args: JavaArgs<'_>,
) -> ResultType<Option<LocalJavaObject<'a>>> {
#[cfg(feature = "log")]
crate::trace!(
"Calling static object method {} with {} args",
method.get_java_signature(),
args.len()
);
let obj = unsafe {
let args = self.convert_args(
args,
#[cfg(feature = "type_check")]
method.get_signature(),
)?;
self.methods.CallStaticObjectMethodA.unwrap()(
self.env,
class.class(),
method.id(),
args.as_ptr(),
)
};
if self.is_err() {
#[cfg(feature = "log")]
log::debug!("Method {} threw an error", method.get_java_signature());
Err(self.get_last_error(file!(), line!(), true, "CallStaticObjectMethod failed")?)
} else {
self.return_method_object(obj, method)
}
}
define_call_methods!(
call_int_method,
call_static_int_method,
CallIntMethodA,
CallStaticIntMethodA,
i32,
r,
r
);
define_call_methods!(
call_long_method,
call_static_long_method,
CallLongMethodA,
CallStaticLongMethodA,
i64,
r,
r
);
define_call_methods!(
call_float_method,
call_static_float_method,
CallFloatMethodA,
CallStaticFloatMethodA,
f32,
r,
r
);
define_call_methods!(
call_boolean_method,
call_static_boolean_method,
CallBooleanMethodA,
CallStaticBooleanMethodA,
bool,
r,
r != 0
);
define_call_methods!(
call_byte_method,
call_static_byte_method,
CallByteMethodA,
CallStaticByteMethodA,
i8,
r,
r
);
define_call_methods!(
call_char_method,
call_static_char_method,
CallCharMethodA,
CallStaticCharMethodA,
u16,
r,
r
);
define_call_methods!(
call_short_method,
call_static_short_method,
CallShortMethodA,
CallStaticShortMethodA,
i16,
r,
r
);
define_call_methods!(
call_double_method,
call_static_double_method,
CallDoubleMethodA,
CallStaticDoubleMethodA,
f64,
r,
r
);
define_call_methods!(
call_void_method,
call_static_void_method,
CallVoidMethodA,
CallStaticVoidMethodA,
(),
r,
r
);
pub fn get_field_id(
&'a self,
class: &'a JavaClass<'a>,
name: String,
signature: JavaType,
is_static: bool,
) -> ResultType<JavaField<'a>> {
#[cfg(feature = "log")]
crate::trace!("Getting field {} with signature {}", name, signature);
let field_name = CString::new(name.clone())?;
let field_signature = CString::new(signature.to_jni_type())?;
let field = unsafe {
if is_static {
self.methods.GetStaticFieldID.unwrap()(
self.env,
class.class(),
field_name.as_ptr(),
field_signature.as_ptr(),
)
} else {
self.methods.GetFieldID.unwrap()(
self.env,
class.class(),
field_name.as_ptr(),
field_signature.as_ptr(),
)
}
};
if self.is_err() || field.is_null() {
Err(self.get_last_error(
file!(),
line!(),
true,
format!("Could not find field '{}'", name).as_str(),
)?)
} else {
Ok(unsafe { JavaField::new(field, signature, class, is_static) })
}
}
fn return_field_object<T: GetSignatureRef>(
&'a self,
res: sys::jobject,
_field: &T,
alt_text: &'static str,
) -> ResultType<Option<JavaObject<'a>>> {
if self.is_err() {
Err(self.get_last_error(file!(), line!(), true, alt_text)?)
} else if res.is_null() {
Ok(None)
} else {
Ok(Some(JavaObject::from(LocalJavaObject::new(
res,
self,
#[cfg(feature = "type_check")]
_field.get_signature_ref().clone(),
))))
}
}
pub fn get_object_field(
&'a self,
field: &JavaObjectField<'_>,
object: &JavaObject<'_>,
) -> ResultType<Option<JavaObject<'a>>> {
#[cfg(feature = "log")]
crate::trace!("Getting object field {}", field.get_signature_ref());
let res =
unsafe { self.methods.GetObjectField.unwrap()(self.env, object.get_raw(), field.id()) };
self.return_field_object(res, field, "GetObjectField failed")
}
pub fn set_object_field(
&'a self,
field: &JavaObjectField<'_>,
object: &JavaObject<'_>,
value: Option<JavaObject<'_>>,
) -> ResultType<()> {
#[cfg(feature = "log")]
crate::trace!("Setting object field {}", field.get_signature_ref());
unsafe {
self.methods.SetObjectField.unwrap()(
self.env,
object.get_raw(),
field.id(),
value
.as_ref()
.map(|v| v.get_raw())
.unwrap_or(ptr::null_mut()),
);
}
if self.is_err() {
Err(self.get_last_error(file!(), line!(), true, "SetObjectField failed")?)
} else {
Ok(())
}
}
pub fn get_static_object_field(
&'a self,
field: &StaticJavaObjectField,
class: &JavaClass<'_>,
) -> ResultType<Option<JavaObject<'a>>> {
#[cfg(feature = "log")]
crate::trace!("Getting static object field {}", field.get_signature());
let res = unsafe {
self.methods.GetStaticObjectField.unwrap()(self.env, class.class(), field.id())
};
self.return_field_object(res, field, "GetStaticObjectField failed")
}
pub fn set_static_object_field(
&'a self,
field: &StaticJavaObjectField,
class: &JavaClass<'_>,
value: Option<JavaObject<'_>>,
) -> ResultType<()> {
#[cfg(feature = "log")]
crate::trace!("Setting static object field {}", field.get_signature());
unsafe {
self.methods.SetStaticObjectField.unwrap()(
self.env,
class.class(),
field.id(),
value
.as_ref()
.map(|v| v.get_raw())
.unwrap_or(ptr::null_mut()),
);
}