In this article you will learn how you can create an instance of Java object from .NET using Javonet. Javonet allows you to initialize any public object defined in Java Jar packages within Java framework and custom packages which you will reference through Javonet. You can create an instance the same way as you would do within Java through public constructor with or without arguments.

Before creating an instance of Java object you should activate Javonet and add reference to your Java package which defines the object you plan to use. All types from Java framework loaded by default with Java JVM will be available without adding any reference to Java packages.

Creating Instance of Java Object
To initialize an Object you should call Javonet.New(…) method which accepts as arguments the name of Java type and constructor arguments. The Java type name should be provided using full qualified type name with namespace. After calling the Javonet.New(…) method you will receive instance of JObject as a result. JObject type is representing instance of any Java class. Operating on JObject you can invoke methods, get/set fields and interact with your Java class instance. JObject holds internally the reference of underlying Java type instance.

Disposing Java Object
Whenever your .NET JObject instance is not used anymore and garbage collected that information will be forwarded to Java side and object will get collected when not referenced on Java side anymore.

Usage Sample
Please see the example below to see how you can create an instance of java.util.Random object and call instance method nextInt:

var rand = Javonet.New("java.util.Random");
int n = rand.Invoke<Int32>("nextInt",50)+1;

To call the parametrized constructor you just need to pass the arguments as additional arguments of Javonet.New(…) method after the type name. Example below shows how to initialize java.util.Random class passing long seed value as argument:

var rand = Javonet.New("java.util.Random",new JPrimitive(1000L));
int n = rand.Invoke<Int32>("nextInt",50)+1;

Notice that in this case the argument is wrapped with JPrimitive class. Java distinguish between boxed (i.e. Long) and unboxed (i.e. long) value types. All value types can be passed using regular .NET types which will get auto converted to corresponding Java values, however if your Java method expects unboxed value types (primitive) you should wrap the argument with JPrimitive instance.

Download this article