Using Value-Type and Reference-Type Arrays
With Javonet, you can use any value-type or reference-type arrays. Arrays can be retrieved from field or property values, returned as method invocation results, or passed as arguments or set to fields and properties. All array operations can be performed both on instance and static elements.
Using arrays is very simple. Value-typed arrays are translated into regular arrays of corresponding Java types. Reference-typed arrays are represented as array of NObject/JObject objects.
Assuming we have a custom .NET Framework DLL with the following class inside:
using System;
namespace TestNamespace
{
public class MyItem
{
public MyItem(string name) { ItemName = name; }
public string ItemName { get; set; }
}
public class ArrayTestClass
{
public string[] GetItems()
{
return new string[] { "item1", "item2", "item3" };
}
public MyItem[] GetRefItems()
{
return new MyItem[] { new MyItem("Item1"), new MyItem("Item2"), new MyItem("Item3") };
}
public void DisplayArray(string[] items)
{
Console.Out.WriteLine(".NET: Displaying value-typed array");
foreach (var item in items)
Console.Out.WriteLine(item);
}
public void DisplayArray(MyItem[] items)
{
Console.Out.WriteLine(".NET: Displaying ref-typed array");
foreach (var item in items)
Console.Out.WriteLine(item.ItemName);
}
}
}
To use method from this class in Java:
// Todo: activate Javonet and add reference to .NET library
// retrieve array of strings
NObject sampleObj = Javonet.New("TestNamespace.ArrayTestClass");
String[] items = sampleObj.invoke("GetItems");
System.out.println("Java: Displaying array values");
for (int i=0; i<items.length;i++)
{
System.out.println(items[i]);
}
// pass array of strings
String[] stringArray = new String[] {"Item1","Item2","Item3"};
sampleObj.invoke("DisplayArray",new Object[] {stringArray});
// retrieve array of .NET objects
NObject[] refArray = sampleObj.invoke("GetRefItems");
System.out.println("Java: Displaying array of .NET objects' item names");
for (NObject element : refArray)
{
System.out.println((String)element.get("ItemName"));
}
// pass array of .NET objects
sampleObj.invoke("DisplayArray",new Object[] {refArray});
// expected output:
//Java: Displaying array values
//item1
//item2
//item3
//.NET: Displaying value-typed array
//Item1
//Item2
//Item3
//Java: Displaying array of .NET objects' item names
//Item1
//Item2
//Item3
//.NET: Displaying ref-typed array
//Item1
//Item2
//Item3
Java
Starting with version 1.4hf34 you can also retrieve a mixed arrays of value and reference types. In such case you will received on Java side an Object[] which will consist of NObject items and Java value types like (float, double, int, etc..).
Was this article helpful?