Skip to content

Commit 7e5aab1

Browse files
Merge pull request #133 from dcz-self/master
readme: Improve docs on creating arrays
2 parents 727db73 + 95ddfee commit 7e5aab1

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

README.md

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ let state = jvm.static_class("java.lang.Thread$State")?;
7979
```rust
8080
let rust_vec = vec!["arg1", "arg2", "arg3", "arg33"];
8181

82-
// Generate a Java List. The Java List implementation is the one that is returned by java.util.Arrays#asList
82+
// Generate a Java List<String>. The Java List implementation is the one that is returned by java.util.Arrays#asList
8383
let java_list_instance = jvm.java_list(
8484
JavaClass::String,
8585
rust_vec)?;
@@ -124,7 +124,13 @@ let my_vec: Vec<String> = vec![
124124
"def".to_owned(),
125125
"ghi".to_owned()];
126126

127+
// Creates List<String>
127128
let i10 = InvocationArg::try_from(my_vec.as_slice())?;
129+
130+
let another_vec: Vec<f64> = vec![0.0, 1.0, 3.6];
131+
132+
// Creates List<Float>
133+
let i11 = InvocationArg::try_from(another_vec.as_slice())?;
128134
```
129135

130136
The `j4rs` apis accept `InvocationArg`s either as references, or values:
@@ -281,7 +287,7 @@ jvm.cast(&instance, "java.lang.Object")?;
281287
### Java arrays and variadics
282288

283289
```rust
284-
// Create a Java array of Strings
290+
// Create a Java array of Strings `String []`
285291
let s1 = InvocationArg::try_from("string1")?;
286292
let s2 = InvocationArg::try_from("string2")?;
287293
let s3 = InvocationArg::try_from("string3")?;
@@ -291,6 +297,24 @@ let arr_instance = jvm.create_java_array("java.lang.String", &[s1, s2, s3])?;
291297
let list_instance = jvm.invoke_static("java.util.Arrays", "asList", &[InvocationArg::from(arr_instance)])?;
292298
```
293299

300+
When creating an array of primitives, each `InvocationArg` item needs to be converted to one containing primitive value.
301+
302+
```rust
303+
let doubles = vec![0.1, 466.5, 21.37];
304+
305+
// Creates Java `double` primitives within a Rust `Vec`
306+
let double_args: Vec<InvocationArg> = doubles.iter()
307+
.map(|value| Ok::<_, J4RsError>(
308+
InvocationArg::try_from(value)?.into_primitive()?
309+
))
310+
.collect::<Result<_, J4RsError>>()?
311+
312+
// Creates an instance of `double []`
313+
let doubles_array = InvocationArg::try_from(
314+
jvm.create_java_array("double", &double_args)?
315+
)?;
316+
```
317+
294318
### Java Generics
295319

296320
```rust

0 commit comments

Comments
 (0)