Step by Step: Create java package and import to use with C# – level 300

Yesterday I explained
that I was able to import java .jar packages for use with .Net
.  Here’s the

First, here is my sample Java class.  (Don’t put this in VS.Net, compile this
with the java compiler):

    1 package
    3 public class Calculator
    4 {
public int
Add(int first, int second)
    6     {
    7         return
first + second;
    8     }
public int
Subtract(int first, int second)
   11     {
   12         return
first – second;
   13     }
public int
Multiply(int first, int second)
   16     {
   17         return
first * second;
   18     }
public float
Divide(int first, int second)
   21     {
   22         return
first / second;
   23     }
   24 }

This is just a sample calculator that I will leverage at the end with my C#
code.  I’ll need to compile this, so I’ll run:


This will create a Calculator.class file.  Next I’ll package that class into
a .jar file:

jar cvf Calculator.jar *.class

This will take all the class files in the directory and put them in
Calculator.jar.  I only have one class, so I’m good to go.  Now, I’ll run JBImp,
with is a .Net utility, to convert the .jar’s Java bytecode to MSIL:

jbimp /t:library Calculator.jar

And you’ll see the following output:

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


Now I have my .Net assembly named ClassLibraryInteropTest.Calculator.dll. 
Note that the utility used the package name (defined internally) to prefix the
assembly name.

Next, create a .Net project to use as a test harness, and add a reference to
this newly created .dll file.  Once you have referenced it, you’ll be able to
use the following C# code:

    1 using
    3 namespace
    4 {
    5     class
    6     {
    7         [STAThread]
    8         static
void Main(string[] args)
    9         {
   10             ClassLibraryInteropTest.Calculator
myCalc = new
   11             Console.WriteLine(myCalc.Add(23,
   13         }
   14     }
   15 }

If you get an error running this code (cannot find assembly Calculator),
rename the assembly: ClassLibraryInteropTest.Calculator.dll to Calculator.dll. 

You get full intellisense about all the methods of the Calculator class, and
essentially, you treat it exactly the same as .Net code because the JBImp
utility actually makes it a .Net assembly.