typed_jni/field/
get.rs

1use typed_jni_core::{FieldID, JNIEnv};
2
3use crate::{LocalObject, ObjectType, TypedRef, builtin::JavaThrowable, core::StrongRef};
4
5/// This trait is implemented for all types that can be the return value of a field get operation.
6///
7/// Supported Types:
8///
9/// * Primitive types: `bool`, `i8`, `u16`, `i32`, `i64`, `f32`, `f64`
10/// * Object types: `LocalObject<Type>`, `Option<LocalObject<Type>>`
11///
12/// # Safety
13///
14/// This trait should not be implemented manually.
15pub unsafe trait Got<'env>: Sized {
16    /// Get the value of a field.
17    ///
18    /// # Safety
19    ///
20    /// * Signature of `Self` must match the signature of `field`.
21    unsafe fn get_of<const STATIC: bool, R: StrongRef>(
22        env: &'env JNIEnv,
23        obj: &R,
24        field: FieldID<STATIC>,
25    ) -> Result<Self, LocalObject<'env, JavaThrowable>>;
26}
27
28macro_rules! impl_got_for_primitive {
29    ($ty:ty, $get:ident) => {
30        unsafe impl<'env> Got<'env> for $ty {
31            unsafe fn get_of<const STATIC: bool, R: StrongRef>(
32                env: &'env JNIEnv,
33                obj: &R,
34                field: FieldID<STATIC>,
35            ) -> Result<Self, LocalObject<'env, JavaThrowable>> {
36                unsafe { env.$get(obj, field).map_err(|err| LocalObject::from_ref(err)) }
37            }
38        }
39    };
40}
41
42impl_got_for_primitive!(bool, get_boolean_field);
43impl_got_for_primitive!(i8, get_byte_field);
44impl_got_for_primitive!(u16, get_char_field);
45impl_got_for_primitive!(i16, get_short_field);
46impl_got_for_primitive!(i32, get_int_field);
47impl_got_for_primitive!(i64, get_long_field);
48impl_got_for_primitive!(f32, get_float_field);
49impl_got_for_primitive!(f64, get_double_field);
50
51macro_rules! impl_got_for_object {
52    ($ty:ty, $ret:ident, $transform:block) => {
53        unsafe impl<'env, T: ObjectType> Got<'env> for $ty {
54            unsafe fn get_of<const STATIC: bool, R: StrongRef>(
55                env: &'env JNIEnv,
56                obj: &R,
57                field: FieldID<STATIC>,
58            ) -> Result<Self, LocalObject<'env, JavaThrowable>> {
59                unsafe {
60                    env.get_object_field(obj, field)
61                        .map(|$ret| $transform)
62                        .map_err(|err| LocalObject::from_ref(err))
63                }
64            }
65        }
66    };
67}
68
69impl_got_for_object!(Option<LocalObject<'env, T>>, v, { v.map(|v| LocalObject::from_ref(v)) });
70impl_got_for_object!(LocalObject<'env, T>, v, {
71    LocalObject::from_ref(v.expect("get: value is null"))
72});