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
use crate::{env::Env, signature::Signature, value::Value, Type};
use jni::objects::{JClass, JObject, JValueGen};

/// A struct wrapping a JClass
pub struct Class<'a> {
  env: &'a Env<'a>,
  class: JClass<'a>,
}

impl<'a> Class<'a> {
  /// Creates a new Class
  ///
  /// # Arguments
  ///
  /// * `env` - The environment
  /// * `class` - The JClass to wrap
  pub fn new(env: &'a Env<'a>, class: JClass<'a>) -> Class<'a> {
    Class { env, class }
  }

  /// Calls a static method on the class
  ///
  /// # Arguments
  ///
  /// * `name` - The name of the method
  /// * `signature` - The signature of the method
  /// * `args` - The arguments to pass to the method
  pub fn call_static_method(
    &self,
    name: &str,
    signature: Signature,
    args: &[Value],
  ) -> jni::errors::Result<JValueGen<JObject<'_>>> {
    let class = &self.class;
    let signature: String = signature.into();

    let mut jni_env = self.env.get_jni_env();
    jni_env.call_static_method(
      class,
      name,
      signature,
      args
        .iter()
        .map(|o| self.env.value(*o))
        .collect::<Vec<JValueGen<&JObject>>>()
        .as_slice(),
    )
  }

  /// Creates an instance of the class
  ///
  /// # Arguments
  ///
  /// * `signature` - The signature of the constructor
  /// * `args` - The arguments to pass to the constructor
  pub fn new_instance(&self, signature: Signature, args: &[Value]) -> jni::errors::Result<JObject> {
    let class = &self.class;
    let signature: String = signature.into();

    let mut jni_env = self.env.get_jni_env();
    jni_env.new_object(
      class,
      signature,
      args
        .iter()
        .map(|o| self.env.value(*o))
        .collect::<Vec<JValueGen<&JObject>>>()
        .as_slice(),
    )
  }

  /// Gets a static field on the class
  /// 
  /// # Arguments
  /// 
  /// * `name` - The name of the field
  /// * `type` - The type of the field
  pub fn get_static_field(
    &self,
    name: &str,
    r#type: Type,
  ) -> jni::errors::Result<JValueGen<JObject<'_>>> {
    let class = &self.class;
    let r#type: String = r#type.to_string();

    let mut jni_env = self.env.get_jni_env();
    jni_env.get_static_field(class, name, r#type)
  }

  /// Get the wrapped class
  pub fn get_class(self) -> JClass<'a> {
    self.class
  }
}