1 use crate::{ 2 objects::JObject, 3 sys::{jclass, jobject}, 4 }; 5 6 /// Lifetime'd representation of a `jclass`. Just a `JObject` wrapped in a new 7 /// class. 8 #[repr(transparent)] 9 #[derive(Debug)] 10 pub struct JClass<'local>(JObject<'local>); 11 12 impl<'local> AsRef<JClass<'local>> for JClass<'local> { as_ref(&self) -> &JClass<'local>13 fn as_ref(&self) -> &JClass<'local> { 14 self 15 } 16 } 17 18 impl<'local> AsRef<JObject<'local>> for JClass<'local> { as_ref(&self) -> &JObject<'local>19 fn as_ref(&self) -> &JObject<'local> { 20 self 21 } 22 } 23 24 impl<'local> ::std::ops::Deref for JClass<'local> { 25 type Target = JObject<'local>; 26 deref(&self) -> &Self::Target27 fn deref(&self) -> &Self::Target { 28 &self.0 29 } 30 } 31 32 impl<'local> From<JClass<'local>> for JObject<'local> { from(other: JClass) -> JObject33 fn from(other: JClass) -> JObject { 34 other.0 35 } 36 } 37 38 /// This conversion assumes that the `JObject` is a pointer to a class object. 39 impl<'local> From<JObject<'local>> for JClass<'local> { from(other: JObject) -> Self40 fn from(other: JObject) -> Self { 41 unsafe { Self::from_raw(other.into_raw()) } 42 } 43 } 44 45 /// This conversion assumes that the `JObject` is a pointer to a class object. 46 impl<'local, 'obj_ref> From<&'obj_ref JObject<'local>> for &'obj_ref JClass<'local> { from(other: &'obj_ref JObject<'local>) -> Self47 fn from(other: &'obj_ref JObject<'local>) -> Self { 48 // Safety: `JClass` is `repr(transparent)` around `JObject`. 49 unsafe { &*(other as *const JObject<'local> as *const JClass<'local>) } 50 } 51 } 52 53 impl<'local> std::default::Default for JClass<'local> { default() -> Self54 fn default() -> Self { 55 Self(JObject::null()) 56 } 57 } 58 59 impl<'local> JClass<'local> { 60 /// Creates a [`JClass`] that wraps the given `raw` [`jclass`] 61 /// 62 /// # Safety 63 /// 64 /// `raw` may be a null pointer. If `raw` is not a null pointer, then: 65 /// 66 /// * `raw` must be a valid raw JNI local reference. 67 /// * There must not be any other `JObject` representing the same local reference. 68 /// * The lifetime `'local` must not outlive the local reference frame that the local reference 69 /// was created in. from_raw(raw: jclass) -> Self70 pub unsafe fn from_raw(raw: jclass) -> Self { 71 Self(JObject::from_raw(raw as jobject)) 72 } 73 74 /// Returns the raw JNI pointer. as_raw(&self) -> jclass75 pub fn as_raw(&self) -> jclass { 76 self.0.as_raw() as jclass 77 } 78 79 /// Unwrap to the raw jni type. into_raw(self) -> jclass80 pub fn into_raw(self) -> jclass { 81 self.0.into_raw() as jclass 82 } 83 } 84