Language: EN

csharp-ikvm-net

How to integrate Java and .NET with IKVM

IKVM is an open-source implementation of the Java Virtual Machine (JVM) for the .NET environment written in C#.

IKVM provides interoperability between seemingly incompatible development worlds, allowing Java code to be executed on the .NET platform. It provides an interface for programs written in .NET languages to interact with Java libraries.

This means that developers can use existing Java libraries and applications in .NET projects without having to completely rewrite the code.

IKVM consists of

  • A Java Virtual Machine (JVM) implemented in .NET
  • An implementation of Java class libraries in .NET
  • A tool that translates Java bytecode (JAR files) to .NET IL (DLL or EXE files).
  • Tools that enable interoperability between Java and .NET
  • A complete JRE/JDK 8 runtime image.

Classes, methods, and Java libraries can be used directly from .NET code and vice versa. This allows us to reuse specific functionalities of an existing library or platform without having to perform a complete code conversion.

The library is designed to optimize performance and minimize conversion and execution overhead. This allows applications using IKVM to run efficiently and without (too many) issues.

How to use IKVM

We can easily add the library to a .NET project through the corresponding Nuget package.

Install-Package IKVM

Here are some examples of how to use IKVM extracted from the library documentation.

Using Java code in C#

Let’s see how we can use Java code directly in our .NET program, thanks to IKVM. Here’s an example.

// Create an instance of a Java class
var javaInstance = new java.util.Date();

// Invoke a Java method from .NET
javaInstance.setDate(10);

// Get a result from a Java method
var result = javaInstance.getDate();

// Print the result
Console.WriteLine(result);

In this example, we use IKVM to create an instance of the Java class java.util.Date. Then, we use the setDate method to set the day of the month to 10. Finally, we call the getDate method to get the updated day of the month and print the result.

Adding a .jar file to our project

We can also add a Java library (.jar) as if it were an assembly or DLL in .NET.

To do this, we need to edit our project’s configuration file and simply add a reference to our .jar file.

<ItemGroup>
  <PackageReference Include="IKVM" Version="Version" />
</ItemGroup>

<ItemGroup>
  <IkvmReference Include="..\..\ext\helloworld\helloworld-2.0.jar" />
</ItemGroup>

The functions defined in this file will be accessible from our program in .NET.