Using a Java class in .Net

This item was filled under [ .Net ]

It might sound a little complex using Java package in .Net but trust me, the interoperability is quite easy ;) I’ll explain the procedure in few simple steps:

1. Create a simple Java class, for e.g.

public class CalculatorX {

public int Add(int firstNum, int secondNum)
{
return firstNum + secondNum;
}

}

2. Compile it to create a .class

> javac calculatorx.java

3. In case you have more than one class, you may package it into a JAR file.

> jar cvf calculatorx.jar *.class

4. Now, run *JBImp. JBImp is a Microsoft Java-language bytecode to MSIL converter.

> jbimp /t:library calculatorx.class

(or<i> calculatorx.jar</i> if you have created a package)

You’ll get the following output:

“Microsoft (R) Java-language bytecode to MSIL converter version 2.0.50727.42
for Microsoft (R) .NET Framework version 2.0.50727
Copyright (C) Microsoft Corp 2000-2002. All rights reserved.

Created CalculatorX.dll”

6. Here you go! Your .Net assembly named CalculatorX.dll is ready =)

7. Next, create a .Net project. Add a reference to the newly created .dll file and try it out!

(See the sample code below)

static void Main(string[] args)
{
CalculatorX c1 = new CalculatorX();
Console.Write(c1.Add(1, 2).ToString());
}

*JBImp - you can find JBImp located in your \Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin directory.

Rate this topic:
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...
Popularity: 155 views
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

8 Comments on “Using a Java class in .Net”

  • 21 January, 2008, 23:48

    You have done a very good Job,,
    it quite amazing …………..

  • Abdul Mannan
    21 January, 2008, 23:56

    hmmmm…….. nice dude :-)

  • 22 January, 2008, 8:35

    Thanks mate! :D

  • faraz
    22 January, 2008, 9:59

    nice one.. from where to get vs 8?

    // this black theme on blog is gud but cant see comment, name and email textboxes clearly ( no visible boundries )

  • faraz
    22 January, 2008, 10:12

    for more info ( features/limitations ) about this tool :

    http://msdn2.microsoft.com/en-us/library/y9teabc2(VS.80).aspx

  • 22 January, 2008, 21:15

    Useful ! Indeed

  • 29 May, 2008, 8:28

    mmmm, thanks for info..

  • Resih
    5 September, 2008, 4:42

    Awesome! this has just saved me hours and hours of converting old (but good) java code to C#. Thanks for the info!

Leave a Comment