csharp-ikvm-net

How to integrate Java and .NET with IKVM

  • 3 min

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

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

This means developers can use existing Java libraries and applications in .NET projects without needing 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 runtime image of JRE/JDK 8.

Java classes, methods, and libraries can be used directly from .NET code and vice versa. This way we can reuse specific functionalities from 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’s 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);
Copied!

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 a DLL in .NET.

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

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

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

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