Click here to Skip to main content
Click here to Skip to main content

Using Java Classes in your .NET Application

By , 23 Mar 2006
 

Introduction

Suppose you have been asked to migrate an existing multi-tier application to .NET where the business layer is written in Java. Normally you would have no option but to recode and port the entire application to any .NET language (e.g. C#).  However this is where IKVM.NET comes to the rescue.

IKVM.NET is an open source implementation of Java for Mono /Microsoft .NET Framework and makes it possible both to develop .NET applications in Java, and to use existing Java API's and libraries in applications written in any .NET language. It is written in C# and the executables, documentation and source code can be downloaded from here.

IKVM.NET consists of the following three main parts:

  1. A Java Virtual Machine implemented in .NET
  2. A .NET implementation of the Java class libraries
  3. Tools that enable Java and .NET interoperability

However before we get any further into this topic, let’s discuss about few of the main components of the IKVM.NET package which we would be using later in this article.

  • IKVM.Runtime.dll: The VM runtime and all supporting code containing the byte code JIT compiler/verifier, object model remapping infrastructure and the managed .NET re-implementations of the native methods in Classpath. 
  • IKVM.GNU.Classpath.dll: Compiled version of GNU Classpath, the Free Software Foundation's implementation of the Java class libraries, plus some additional IKVM.NET specific code. 
  • ikvm.exe: Starter executable, comparable to java.exe ("dynamic mode").
  • ikvmc.exe: Static compiler. Used to compile Java classes and jars into a .NET assembly ("static mode").

Now back to our problem of migrating the existing Java business classes so that they can be accessed by the newly proposed .NET application. We would also like to use the various existing Java API and libraries in our .NET application.  Let’s start by doing just that.

Setting Up IKVM.NET

Download the binary distribution from the sourceforge site and unzip the contents to C:\ikvm (or X:\ikvm where X is your drive). You would find the ikvm executables and DLLs in the C:\ikvm\bin directory.  Open a command or shell window, cd to C:\ikvm\bin, and type ‘ikvm’.

If your system is operating correctly, you should see the following output:

usage: ikvm [-options] <class> [args...] (to execute a class) or ikvm -jar [-options] <jarfile> [args...] (to execute a jar file)

For Linux based systems, the setup is similar as above. This is all you need to do for running the demo application.

Our Demo Java Business Class (JavaToNet.java)

public class JavaToNet 
{
    public static void main(String[] args) 
    {
        System.out.println("This is a demonstration Program which\n");
        System.out.println("shows the conversion of Java class to\n");
        System.out.println("a .NET dll\n");
    }
    public  static double AddNumbers(double a,double b){
    double c = 0;
    c = a + b;
    return c;    
    }
    public  static double SubNumbers(double a,double b){
        double c = 0;
        c = a - b;
        return c;    
        }
    public  static double MulNumbers(double a,double b){
        double c = 0;
        c = a * b;
        return c;    
        }
    public  static double DivNumbers(double a,double b){
        double c = 0;
        c = a / b;
        return c;    
        }
}

Our Java class is very simple. It has four functions for add, subtract, multiply and divide that take two double values and return a result. Our objective is to access these functions through our C# application. Compile the above Java file to get the JavaToNet.class. We will use this Java class file to generate the .NET DLL to be referenced in our C# program.

Using IKVM.NET to Convert Java Class to .NET DLL

Copy the above Java class file (JavaToNet.class) to the C:\ikvm\bin directory. Now run the following command:

This would create the JavaToNet.dll from the JavaToNet.class file. There are other command line option for ikvmc.exe. For example: ‘ikvmc –target:exe javaToNet.class’ would create an EXE and not a DLL. You can get all the options by typing ‘ikvmc’ in the command line.

Setting Up Your .NET Development Environment

  1. Start by creating a C# Windows application project. 

  2. Drag and drop controls into the form as shown:

  3. Add the following DLLs as references to the project. Both DLLs are present in the C:\ikvm\bin folder.

    • JavaToNet.dll
    • IKVM.GNU.Classpath.dll
  4. Add the following code to the button click event of the ‘Calculate’ button:

    private void btnCal_Click(object sender, System.EventArgs e)
    {
    if (rdAdd.Checked == true)
        {
        txtResult.Text = Convert.ToString(JavaToNet.AddNumbers
    	(Convert.ToDouble(txtNum1.Text),Convert.ToDouble(txtNum2.Text)));
        }else if (rdSub.Checked ==true)
        {
        txtResult.Text = Convert.ToString(JavaToNet.SubNumbers
    	(Convert.ToDouble(txtNum1.Text),Convert.ToDouble(txtNum2.Text)));                
        }
        else if (rdMul.Checked == true)
        {
        txtResult.Text = Convert.ToString(JavaToNet.MulNumbers
    	(Convert.ToDouble(txtNum1.Text),Convert.ToDouble(txtNum2.Text)));                
        }
        else
        {
        txtResult.Text = Convert.ToString(JavaToNet.DivNumbers
    	(Convert.ToDouble(txtNum1.Text),Convert.ToDouble(txtNum2.Text)));            
        }
    }
  5. Add the following using directive on the top of the *.cs file:

    using TimeZone = java.util.TimeZone;
  6. Add the following code to the button click event of the ‘Time Zone’ button.

    private void btnTimeZone_Click(object sender, System.EventArgs e)
    {
    MessageBox.Show(TimeZone.getDefault().getDisplayName());
    }
  7. Compile and run the application. The C# application would now call the AddNumbers(), SubNumbers(), MulNumbers() and DivNumbers() functions present in the JavaToNet.dll and return the result.

  8. Click on the ‘Time Zone’ button. The application accesses the java.util.TimeZone class and displays the exact time zone of the place.

Conclusion

Since these methods had originally been written in Java, IKVM.NET provides us an easy and viable way to access those classes and methods from a .NET application. Similarly as shown above in the ‘Time Zone’ example, you can access most of the existing Java packages (e.g. java.io, java.util, etc.) and use them in your application.

However there are certain drawbacks. IKVM.NET, while still being actively developed, has limited support for AWT classes and hence porting Java GUI can be ruled out at present. Also some of the default Java classes are still being ported so you might not get all the functionalities you require. Also if your application depends on the exact Java class loading semantics, you might have to modify it to suit your needs.

History

  • 03-25-06 Initial publication

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Chayan
Web Developer
India India
Member
Chayan Ray has been working as a Technical Consultant in a CMM level 5 company in India. His technical domain includes ASP.NET, C#, PHP, Perl, Cold Fusion, MySQL and MSSQL 2000.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionError Message ->IKVMC0002: Output File is "JavaToNet.dll"memberMrKyaw20 Jan '13 - 21:24 
Hi Mr Chayan,
 
I started to use your ikvmc as below
 
C:\ikvm-7.2.4630.5\bin>ikvmc -target:library JavaToNet.class
IKVM.NET Compiler version 7.2.4630.5
Copyright (C) 2002-2012 Jeroen Frijters
http://www.ikvm.net/
 
note IKVMC0002: Output file is "JavaToNet.dll"
 
C:\ikvm-7.2.4630.5\bin>
 
After that I got JavaToNet.dll then add References in .NET project.
 
Another error came out as below
Consider app.config remapping of assembly "IKVM.Runtime, Culture=neutral, PublicKeyToken=13235d27fcbfff58" from Version "0.18.0.0" [] to Version "7.2.4630.5" [..\..\..\..\..\..\..\..\ikvm-7.2.4630.5\bin\IKVM.Runtime.dll] to solve conflict and get rid of warning.
C:\Windows\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets : warning MSB3247: Found conflicts between different versions of the same dependent assembly.
C:\Windows\Microsoft.NET\Framework\v3.5\Csc.exe /noconfig /unsafe- /checked- /nowarn:1701,1702 /nostdlib- /errorreport:prompt /warn:4 /baseaddress:285212672 /define:DEBUG;TRACE /reference:bin\Debug\IKVM.GNU.Classpath.dll /reference:..\..\..\..\..\..\..\..\ikvm-7.2.4630.5\bin\JavaToNet.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /debug+ /debug:full /filealign:4096 /optimize- /out:obj\Debug\WindowsApplication2.exe /resource:obj\Debug\WindowsApplication2.Form1.resources /target:winexe /warnaserror- /win32icon:App.ico AssemblyInfo.cs Form1.cs
C:\InterOPs(Java&NET)\csharpikvm_src\application_src\NET\JavaToNet\Form1.cs(217,5): error CS0012: The type 'java.lang.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'IKVM.OpenJDK.Core, Version=7.2.4630.5, Culture=neutral, PublicKeyToken=13235d27fcbfff58'.
c:\ikvm-7.2.4630.5\bin\JavaToNet.dll: (Related file)
 
It was working using your generated DLL in this .NET project and pls advise me.
 
Thanks and best regards
QuestionGetting errors while converting Jar to dll using IKVM - please help!membersonam5021732 Jan '13 - 3:24 
E:\Sonam Dhabria\ikvmbin-7.2.4630.5\ikvm-7.2.4630.5\bin>ikvmc genericclient.jar
-target:library
IKVM.NET Compiler version 7.2.4630.5
Copyright (C) 2002-2012 Jeroen Frijters
http://www.ikvm.net/
note IKVMC0002: Output file is "genericclient.dll"
warning IKVMC0100: Class "javax.xml.rpc.ServiceFactory" not found
warning IKVMC0100: Class "javax.xml.rpc.Service" not found
warning IKVMC0100: Class "javax.xml.rpc.encoding.TypeMappingRegistry" not found
warning IKVMC0100: Class "org.apache.axis.encoding.TypeMappingRegistry" not foun
d
warning IKVMC0100: Class "javax.xml.rpc.encoding.TypeMapping" not found
warning IKVMC0100: Class "org.apache.axis.encoding.TypeMapping" not found
warning IKVMC0100: Class "org.apache.axis.encoding.ser.BeanSerializerFactory" no
t found
warning IKVMC0100: Class "org.apache.axis.encoding.ser.BeanDeserializerFactory"
not found
warning IKVMC0100: Class "javax.xml.rpc.encoding.SerializerFactory" not found
warning IKVMC0100: Class "javax.xml.rpc.encoding.DeserializerFactory" not found
warning IKVMC0100: Class "javax.xml.rpc.Call" not found
warning IKVMC0100: Class "javax.xml.rpc.ParameterMode" not found
warning IKVMC0111: Emitted java.lang.NoClassDefFoundError in "com.tcs.ws.service
.genericclient.GenericAppClient.invokeService(Ljava.util.List;)Ljava.lang.Object
;"
      ("javax.xml.rpc.ServiceFactory")
QuestionGetting Class not found errors while converting jar to dll using IKVM - please help!!!!membersonam5021732 Jan '13 - 3:23 
E:\ikvmbin-7.2.4630.5\ikvm-7.2.4630.5\bin>ikvmc genericclient.jar
-target:library
 
IKVM.NET Compiler version 7.2.4630.5
Copyright (C) 2002-2012 Jeroen Frijters
http://www.ikvm.net/
 
note IKVMC0002: Output file is "genericclient.dll"
warning IKVMC0100: Class "javax.xml.rpc.ServiceFactory" not found
warning IKVMC0100: Class "javax.xml.rpc.Service" not found
warning IKVMC0100: Class "javax.xml.rpc.encoding.TypeMappingRegistry" not found
warning IKVMC0100: Class "org.apache.axis.encoding.TypeMappingRegistry" not foun
d
warning IKVMC0100: Class "javax.xml.rpc.encoding.TypeMapping" not found
warning IKVMC0100: Class "org.apache.axis.encoding.TypeMapping" not found
warning IKVMC0100: Class "org.apache.axis.encoding.ser.BeanSerializerFactory" no
t found
warning IKVMC0100: Class "org.apache.axis.encoding.ser.BeanDeserializerFactory"
not found
warning IKVMC0100: Class "javax.xml.rpc.encoding.SerializerFactory" not found
warning IKVMC0100: Class "javax.xml.rpc.encoding.DeserializerFactory" not found
warning IKVMC0100: Class "javax.xml.rpc.Call" not found
warning IKVMC0100: Class "javax.xml.rpc.ParameterMode" not found
warning IKVMC0111: Emitted java.lang.NoClassDefFoundError in "com.tcs.ws.service
.genericclient.GenericAppClient.invokeService(Ljava.util.List;)Ljava.lang.Object
;"
      ("javax.xml.rpc.ServiceFactory")
QuestionGetting Class not found errors while converting jar to dll using IKVMmembersonam5021732 Jan '13 - 3:22 
E:\ikvmbin-7.2.4630.5\ikvm-7.2.4630.5\bin>ikvmc genericclient.jar
-target:library
 
IKVM.NET Compiler version 7.2.4630.5
Copyright (C) 2002-2012 Jeroen Frijters
http://www.ikvm.net/
 
note IKVMC0002: Output file is "genericclient.dll"
warning IKVMC0100: Class "javax.xml.rpc.ServiceFactory" not found
warning IKVMC0100: Class "javax.xml.rpc.Service" not found
warning IKVMC0100: Class "javax.xml.rpc.encoding.TypeMappingRegistry" not found
warning IKVMC0100: Class "org.apache.axis.encoding.TypeMappingRegistry" not foun
d
warning IKVMC0100: Class "javax.xml.rpc.encoding.TypeMapping" not found
warning IKVMC0100: Class "org.apache.axis.encoding.TypeMapping" not found
warning IKVMC0100: Class "org.apache.axis.encoding.ser.BeanSerializerFactory" no
t found
warning IKVMC0100: Class "org.apache.axis.encoding.ser.BeanDeserializerFactory"
not found
warning IKVMC0100: Class "javax.xml.rpc.encoding.SerializerFactory" not found
warning IKVMC0100: Class "javax.xml.rpc.encoding.DeserializerFactory" not found
warning IKVMC0100: Class "javax.xml.rpc.Call" not found
warning IKVMC0100: Class "javax.xml.rpc.ParameterMode" not found
warning IKVMC0111: Emitted java.lang.NoClassDefFoundError in "com.tcs.ws.service
.genericclient.GenericAppClient.invokeService(Ljava.util.List;)Ljava.lang.Object
;"
("javax.xml.rpc.ServiceFactory")
Questionikmv class java to .net c#memberMember 455975016 Jun '12 - 3:37 
Hello, please help me
 
I have class java i need translate to c#
 
best regards
 
Leo - leo@lgmultimedia.com
QuestionHow to use IKVM without creating dllmemberNarVish25 May '12 - 3:29 
Thank you for the nice article, Chayan. Can you let me know to use IKVM without creating dll for java class. Thanks in advance.
QuestionThank you...memberrajendranmca200824 Oct '11 - 21:42 
Realy good article...
 
Thanks,
Rajendran
QuestionThanksmembersanya.fesak21 Sep '11 - 19:12 
Where to get Java?
GeneralIKVM Framework is Updatedmembermajed.idrees16 Apr '11 - 16:20 
I just want to inform you that the Library has been updated,
it is not using "IKVM.GNU.Classpath.dll" any more, they replaced it with "IKVM.OpenJDK.Core.dll"
No muslim is a muslim if he
does not believe in gesus peace be up him...
so Islam is the only solution...

Questionthe architecture in IKVM ?memberNguyen_Chuong21 Feb '11 - 4:54 
Somebody research the architecture in IKVM ?JNI in java for Native Language. bu IKVM support that. That is .net application
GeneralJar to Native Dllmemberdummy programmer241 Dec '10 - 15:13 
Thanks... I am working on a project which requires me to convert our API(jar) to dll, such that native languages such as C or Perl can use it. I have been googling but couldnt find nice tools for converting jar to dll.What is the difference between native language dll and .Net dll? As IKVM convert jar to .Net dll,can i use that .Net dll for writing a C program or Perl program? Or shall i be using some other tool which converts jar to dll, if so do you know any of those tools? Appreciate your help Smile | :)
GeneralRe: Jar to Native DllmemberChayan1 Dec '10 - 22:08 
Technically you can call a .NET dll like a com object, using Com Callable Wrapper (http://msdn.microsoft.com/en-us/library/f07c8z1c.aspx[^]).
For Perl, if you can upgrade to Perl.NET, then you can call them directly. Not sure about C though.
Hope this helps.
GeneralRe: Jar to Native Dllmemberdummy programmer242 Dec '10 - 4:11 
Thanks..I am new to .Net thing, am basically a java programmer. So do you know any nice tutorials for me to follow such that i can use Com callable wrapper to call the dll and use it from perl and C.
GeneralMy vote of 5memberDilushaM9 Jul '10 - 9:04 
thanx!
Generalusing a jar file with dependent jarsmemberIthilienX26 Oct '08 - 14:14 
I am working on an integration piece with this. However, ikvmc doesn't seem to work for jars having dependent jars. Is there a way round this restriction? Or is it entirely infeasible?
 
thanks.
AnswerRe: using a jar file with dependent jarsmemberRini Jackson14 Mar '12 - 5:20 
The class loader ikvm.runtime.ClassPathAssemblyClassLoader supports dynamically loading classes and resources from the java classpath.
 
if your jar depending on other jars that are taken from the java classpath
you need to specify the -classloader option for the ikvmc tool when compiling :
ikvmc -out:outputDllName.dll -classloader:ikvm.runtime.ClassPathAssemblyClassLoader PathToJarsFolder/*.jar
where PathToJarsFolder contains all the 3rd parties that are taken from the java classpath.
 
you can read more about ikvm.runtime.ClassPathAssemblyClassLoader here
http://weblog.ikvm.net/PermaLink.aspx?guid=8a457a80-1e5f-4182-8f78-b2cd67845553[^]
GeneralRe: using a jar file with dependent jarsmemberNitin Sawant30 Nov '12 - 0:40 
Hi,
I am trying to get dll out of bunch of some LanguageTool jars
http://languagetool.org/[^]
 
I am constantly getting class not found errors.
 
Help appreciated
============================================
The grass is always greener on the other side of the fence

QuestionHas Dependent Jar files?memberMHSrinivasan19 Jun '08 - 0:15 
Will IKVM work if the jar i'm converting has external references to another jars?
 
u can reach me in
mhsrinivasan@yahoo.com

GeneralProblem with IKVMmemberAskalo6 Jul '07 - 5:37 
Hi,
I have tried to use IKVM in order to convert a parser called Chaos from java to .Net. The result is this:
 
C:\ikvm-0.34.0.2\bin>ikvmc -target:library chaos\lib\chaos.jar chaos\ext\sicstus\jasper.jar
 
Warning IKVMC0107: skipping resource (name clash): "META-INF/MANIFEST.MF"
Note IKVMC0002: output file is "chaos.dll"
Note IKVMC0003: automatically adding reference to "C:\ikvm-0.34.0.2\bin\IKVM.GNU.Classpath.dll"
Warning IKVMC0100: class"com.sun.org.apache.xerces.internal.impl.io.MalformedBy
teSequenceException" not found System.NotSupportedException: The invoked member is not supported in a dynamic module.
at System.Reflection.Emit.TypeBuilder.GetMethodImpl(String name,BindingFlags
bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
at System.Type.GetMethod(String name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
at IKVM.Internal.DynamicTypeWrapper.JavaTypeImpl.GetBaseFinalizeMethod(Type type, Boolean& clash)
at IKVM.Internal.DynamicTypeWrapper.JavaTypeImpl.GenerateMethod(Int32 index,
Boolean unloadableOverrideStub)
at IKVM.Internal.DynamicTypeWrapper.JavaTypeImpl.LinkMethod(MethodWrappermw)
at IKVM.Internal.DynamicTypeWrapper.LinkMethod(MethodWrapper mw)
at IKVM.Internal.MethodWrapper.Link()
at IKVM.Internal.ClassFile.ConstantPoolItemMethodref.Link(TypeWrapper thisType, Hashtable classCache)
at IKVM.Internal.ClassFile.Link(TypeWrapper thisType, Hashtable classCache)
at IKVM.Internal.DynamicTypeWrapper.JavaTypeImpl.Finish()
at IKVM.Internal.DynamicTypeWrapper.Finish()
at IKVM.Internal.CompilerClassLoader.Compile(CompilerOptions options)
at IkvmcCompiler.RealMain(String[] args)
 
how can I resolve the problem?
Thanks
GeneralDoes it only work with static methodmemberYeast2725 Sep '06 - 3:04 
I have tried to convert Preprocess.class to dll. It seems to work fine. however when I use the dll file as reference, the method that should be there doesn't show up. I tried to change the java file so that the method are static methods, however the problem become static method cannot have non-static variable and thus it could not compile to form .class. What should I do?
Generalget a error that "unsupported class file version:"memberdevesh.kumar6 Jul '06 - 23:49 
HI,
I have a compiled java class file.
when i am trying to convert it in the dll a error msg occur.
Error: unsupported class fiel version: <49.0>.
please help me to solve the problem.
 
Regards,
Devesh Kumar
 
devesh kumar
GeneralIKVM.NET violates Java and .NET standards!memberVitaly Shelest22 Jun '06 - 3:02 
I do the same easy but use the standard JVM and Microsoft .NET technology.
See examples
here

QuestionHelp regarding IKVMC toolmembersurjithpk12 Apr '06 - 2:13 
I compile a java class using the ikvmc tool to generate a dot net dll but I get an error stating that a related class is not found, while that particular missing class is present in the same directory where I am converting that particular class.
 
surjith
AnswerRe: Help regarding IKVMC toolmemberChayan12 Apr '06 - 5:12 
Hi
 
Are you able to compile the java file from that same location?
 
Regards
GeneralRe: Help regarding IKVMC toolmembersurjithpk12 Apr '06 - 17:40 
Actually I don't have the original source of that class file. I have only the compiled classes alone in a separate directory.
 
surjith
Questionwhat about .Net to Javamemberwael_502 Apr '06 - 6:00 
can this library help me to run .Net code in java environment?
AnswerRe: what about .Net to JavamemberChayan2 Apr '06 - 13:50 
Hi
 
To an extent it does. Please refer to http://www.ikvm.net/devguide/java2net.html[^]
 
Regards
Chayan
AnswerRe: what about .Net to JavamemberBill Seddon26 Aug '06 - 5:52 
No, it doesn't produce class files that can run under a JVM. It will produce stubs for .NET assembly classes and methods so that Java code can be compiled in the expectation that those methods will be available in .NET.
 
www.mainsoft.com do have a product that does allow you to create java class files from .NET assemblies. The rub here is that although its free for developers to use, if you want to distribute a ported app it costs lots.
 

GeneralDoesnot work with Java 5!memberShaurya Anand31 Mar '06 - 15:31 
IKVMC doesnot recognize Java 5 signed classes!
AnswerRe: Doesnot work with Java 5!memberFernando Cases9 Oct '08 - 1:59 
try to compile the java code with "javac -target 1.5 xxx.java" before calling "jar vcf xxx.jar" and ikvmc
GeneralInteresting technologymemberDylan Thomas24 Mar '06 - 5:39 
I was not aware of the IKVM project before reading your article. Thanks for bringing that to my attention. I just had to recode a bunch of custom XML processing tools that already existing in Java so I know there's a need out there Smile | :)
 
-- modified at 11:39 Friday 24th March, 2006
GeneralRe: Interesting technologymemberChayan24 Mar '06 - 9:35 
Hi Dylan
 
Thanks for your feedback and support.
 
Regards
Chayan

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 24 Mar 2006
Article Copyright 2006 by Chayan
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid