The purpose of this post is to show how the cloud based service Javonet.io (powered by Javonet) works under the hood. In short Javonet cloud based service https://javonet.io enables you to create a ready-to-use Java JAR package out of any .NET DLL. What the service generates is the strongly typed Java wrappers created out of the provided .NET DLLs.
For the sake of this example, I have created a sample project covering everything I will discuss today, which is:
- Instance and static classes, creating objects
- Usage of .NET methods, fields, properties
Let me walk you through the process of creating Java strongly typed wrapper out of any DLL.
- First, you need navigate to the website hhttps://javonet.io.
- Drop your DLL onto the drop wizard on the web page.
- The service will analyze if your library needs any additional DLLs in order to work correctly and will prompt you if they are needed.
In this example, my library references only .NET Framework libraries, so I am ready to go.
Wait for the job to be completed …
When ready I can download just the jar file or check the source code of the generated wrapper (in this example, GitHub URL is https://github.com/Javonet-io-user/b1a7577e-a3af-4d24-876b-bd015f064273.git). And we are ready to go ?.
Now let me show you how to use the generated JAR package in your Java project and how to invoke the methods that are inside.
Let’s first set up a Java environment. I have created a very simple Java project in Eclipse, containing just a Main class and a reference to the JAR package that we have generated from .NET DLL named result.jar file. And this is all you need to have.
The first thing you have to do is to set your Javonet license. If you forget to do this, you will get an error message:
Now let’s code something simple. The Constructor class here is a simple POCO or POJO class, depending on which technology you use.
Let’s compare how you create the objects in the .NET DLL and in the generated JAR package generated out of this DLL.
var c = new ConstructorClass(1, "a");
ConstructorClass c = new ConstructorClass(3, "a");
As you can see, when calling the methods from the generated JAR package you don’t even realize that there are the .NET methods being in fact called underneath.
Now let me show you how we handle the .NET properties. We expose methods the public get and set methods from .NET DLL:
var p = new PropertyClass(); p.a = 3; Console.WriteLine(p.a);
ropertyClass p = new PropertyClass(); p.seta(3); System.out.println(p.geta());
In the JAR package generation process the properties of methods are named according to Java naming conventions, and get and set properties are named with a prefix.
Static classes behave the same way in .NET and Java.
var add = StaticClass.Add2(2);
In future posts I will discuss more advanced topics like:
- Event and delegates
I hope I showed how seamless writing in Java code can be using Javonet wrappers that call .NET underneath.