Extending a class and wrapping methods
You can extend any class from .NET Framework DLL by extending the Java class with the NObject/JObject type and then call the constructor base constructor by passing the name of the called type and arguments for its constructor as an argument.
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 extend this class and wrap method from this class create the following class:
I code in:
package utils;
import com.javonet.JavonetException;
import com.javonet.api.NObject;
public class ExtendedTestClass extends NObject {
public ExtendedTestClass() throws JavonetException
{
super("TestNamespace.TestClass");
}
public int MultiplyByTwo(int arg) throws JavonetException
{
return this.invoke("MultiplyByTwo", arg);
}
}
And use it like any other Java class
I code in:
// Todo: activate Javonet and add reference to .NET library
// create extended class instance
ExtendedTestClass myExtendedTestClass = new ExtendedTestClass();
// use method from this class
Integer response = myExtendedTestClass.MultiplyByTwo(77);
// write response to console
System.out.println(response);
Was this article helpful?