Minimize Part 4: Using Java in a C# Application

Integrating Java in .NET Applications

There will be many times when you need to incorporate a class library that has been developed in Java with a new or existing .NET application. Of course, the .NET application will likely have been developed in some other language, such as C# or VB, but you'll still want to be able to reuse the Java-based class library functionality in the application. 

Accomplishing this is very straight forward using Ja.NET SE. Because the output of the Ja.NET SE compiler and bam tools are .NET assemblies, all you have to do is compile the Java class library source code using Ja.NET SE compiler and then create a .NET assembly with all of the library classes using the bam tool. Once you've done this, it becomes very simple to reuse the class library functionality in the .NET application.

Creating a C#/Java Application

To illustrate how, let's combine the following C# console application with the 'MyProgram.dll' assembly we created earlier using the bam tool. If you look closely at the code below, you'll see that the C# application has a reference to the class, HelloWorld. This is the Java-based class contained in the 'MyProgram.dll' assembly. To try this yourself, start up your favorite text editor using the command window you already have open, and paste in the following C# code. Then save it to a file named 'MyCSharpProgram.cs'.

public class MyCSharpProgram {
  public static void Main(String[] args) {
    HelloWorld.saySomethingUsingJava("A new message via Java API's");
    HelloWorld.saySomethingUsingDotNet("A new message via .NET framework API's");
  }
}

Next, in the command window, add 'C:\windows\Microsoft.NET\Framework\v3.5' to your PATH. This is necessary, as it gives you access to the installed C# compiler from the command line. To compile the above file, and to add a reference to the MyProgram.dll assembly, invoke the C# compiler on the command line using 'csc /r:MyProgram.dll MyCSharpProgram.cs'. You should see that the C# compiler has created a new .NET executable, MyCSharpProgram.exe in your current directory.

C:\>set PATH=%PATH%;C:\windows\Microsoft.NET\Framework\v3.5
C:\>
C:\>csc /nologo /r:MyProgram.dll MyCSharpProgram.cs
C:\>

Running a C#/Java Application

You don't have to use the Java launcher to run a program that you've created in this way. Instead, you run the .NET program as you normally would, by entering 'MyCSharpProgram' at the command prompt. When you do, you should see the expected output in the console window.

C:\>MyCSharpProgram
A new message via Java API's
A new message via .NET framework API's
C:\>

Of course everything we've just done using the command line compiler can also be done using any one of the Visual Studio tools provided by Microsoft.

Next, let's take a look at how you can use the .NET debugging tools to debug your combined Java and C# application.