How to create NObject with constructor parameters (JavoNet)

109 Views Asked by At

What is the syntax for creating a .Net object from java code (NObject) when the constructor of the .Net object has one or more parameters?

Thanks

2

There are 2 best solutions below

1
lukaszberwid On BEST ANSWER

The answer by erotavlas is correct although the syntax for classes is much simpler and can be done with a one-liner (https://www.javonet.com/java-devs/guides/creating-instance-calling-instance-methods/).

To create .NET object from Java you simply use:

NObject object = Javonet.New("Namespace.ClassName", params...);  

Additional note if your class constructor has array parameter (of any type) you need to cast it to Object array.

int[] arg1;
Javonet.New("Namespace.ClassName", new Object[] {arg1})

Also, you can try new service that will create a strongly typed java wrapper for you (have a read here https://www.javonet.com/blog/more-about-javonet-io/)

0
erotavlas On

I figured it out in case it wasn't obvious from the documentation

Add your reference to the dll using

Javonet.addReference()

Get the type (class name)

NType test = Javonet.getType("Namespace.Classname");

Call constructor with zero or more parameters

NObject obj = test.create(parameter1,parameter2, parameter3,.....etc);