Creating instance and calling instance methods
Javonet lets you create instances of any type from .NET Framework DLL. Assuming we have a custom .NET Framework DLL with the following class inside
using System;
namespace TestNamespace
{
public class TestClass
{
public TestClass() { }
~TestClass()
{
Console.WriteLine("Displaying object from .NET destructor message");
}
public static int MyStaticField { get; set; }
public int MyInstanceField { get; set; }
public static string SayHello(string name)
{
return "Hello " + name;
}
public int MultiplyByTwo(int arg)
{
return arg * 2;
}
public T MyGenericMethod<T>(T arg1)
{
return arg1;
}
public K MyGenericMethodWithTwoTypes<T, K>(T arg1)
{
return default(K);
}
public void MethodWithRefArg(ref int arg)
{
arg = arg + 44;
}
public string PassTypeArg(Type myType)
{
return myType.ToString();
}
public string MethodWithEnumArg(SampleEnum value)
{
return value.ToString();
}
}
}
To create instance and invoke instance method from this class:
// Todo: activate Javonet and add reference to .NET library
// create instance
NObject sampleObject = Javonet.New("TestNamespace.TestClass");
// call instance method
Integer response = sampleObject.invoke("MultiplyByTwo", 50);
// write response to console
System.out.println(response);
Javonet calls are very similar to regular .NET or Java calls, with a little bit of reflection style. Value-type results are automatically converted into .NET Framework DLL types so you can safely assign them to .NET Framework DLL variables. Reference-type results must be assigned to NObject\JObject variable.
Any calls to .NET or Java objects using Javonet can be shortened and simplified using Javonet Fluent interface.
Was this article helpful?