Calling Java Classes Directly from .NET

Calling Java Classes Directly from .NET

As the frequency of .NET and Java applications increases, we’re headed for an interoperability imperative—we have to get both sides to work together. One way to do that is by adding an interoperability layer that gives .NET direct access to Java classes.

t’s a fact that most production environments now use a mixture of both Java and .NET, despite all the partisan disputes over which side should “win.” To be prudently responsible in the face of this business reality, it is imperative that developers get both sides to work together. Interoperability is no longer an option: fortunately, you do have some options for choosing the best path for achieving interoperability for your project.

Your specific interoperability needs may vary, based on your current systems and project specifications. Perhaps you already have some perfectly good “legacy” Java code that you don’t need to change, but want to extend with new .NET components. Or, you’re creating a new system, and want to assign tasks to the better-suited platform, so you’re using J2EE’s Enterprise Java Beans (EJBs) for the scalable back-end system, and .NET Windows Forms to create a rich desktop GUI. In either case, you may need direct access to Java classes from .NET. This article briefly discusses the major interoperability methods available and highlights some issues to consider as you make your interoperability selection, and demonstrate class-level interop with a specific example.

Click here to see or hide the author’s description of other interoperability methods.

In addition, Web services use a SOAP-based communications mechanism that’s inherently slower than alternative binary communications mechanisms. Web services are also not well-suited for passing custom objects between Java and .NET as parameters and return values.

Visual J#

.NET supports development of systems using multiple languages concurrently. One way to support Java/.NET interoperability is to translate the Java code directly into .NET’s MSIL (Microsoft Intermediate Language) rather than into Java bytecodes. Although Microsoft can’t call its J# language Java, J# really is a way to compile Java code for .NET. Unfortunately, J# a significant limitation: it’s legally limited to the Java supported by JDK 1.1.4 plus JDK1.2’s collection classes. Using J# works only when these limitations don’t matter to you, and when you have access to the original Java source. However, when the Java code you need uses more advanced features, including just about any J2EE feature such as EJBs or servlets, or when you don’t have the source, J# isn’t a good choice.

Java Native Interface (JNI)

Java code can access, and be accessed by, non-Java code via the Java Native Interface (JNI). JNI is mainly suited for accessing Java code running in a standalone JVM on the same machine as your .NET code, and can be difficult to use. If you’re communicating with Java code on a different machine, or running in a J2EE application server, you may have problems. There are some third-party products that may help: JuggerNET, from CodeMesh ) is one example.

BytecodeTranslation

It may be possible to convert the compiled Java bytecodes to .NET MSIL so that you can link it directly into your .NET program. Microsoft’s J# distribution includes a tool called jbimp.exe that converts Java bytecodes to MSIL at compile time. Of course, jbimp.exe has many of the same limitations as J# in that it can convert only bytecodes from JDK 1.1.4 and earlier (plus JDK 1.2 collections. Unlike J#, however, jbimp.exe works without source code. IKVM.NET is an intriguing open-source project that translates Java bytecodes to MSIL as needed at runtime. In theory, IKVM.NET should allow any Java code to run on the .NET platform. However, the project is at a very early stage and far from complete, but certainly worth following for the future.
Close
Runtime Bridges

Perhaps the most natural interoperability method is to run the Java code in a JVM, the .NET code in a CLR, and use a runtime bridge to manage the communications between them. In this scenario, the .NET code calls .NET classes and objects that act as proxies for the Java classes and objects. The proxies manage the communication; the calling .NET classes aren’t even aware that they’re ultimately calling Java classes. A runtime bridge provides interoperability for a wide variety of architectures, because the Java code and the .NET code can be on different machines, the Java code can run in a standalone JVM or in a J2EE application server, and the solution provides interoperability for any JDK version. As with bytecode translation solutions, you need only the Java bytecodes, not the source.

There are several runtime bridges commercially available. The code for this article uses JNBridgePro from JNBridge. See the related resources section of this article for other bridge products.

In the remainder of this article, you’ll see how to use JNBridgePro to solve a real-world interoperability problem.

Build a Logging Example

Most software systems of any size or complexity contain a logging facility. Good logging packages exist for both Java (log4J) and .NET (log4N, which is the .NET equivalent of log4J). However, if a system contains both .NET and Java components, each side would be logged into its own logging package, which would generate two log files and make it difficult to collate or correlate the events logged. If you could instead use a single logging package to log to a single log file, you could easily see the sequence in which .NET-originated and Java-originated events took place. A single logging package also simplifies handling timing and file access conflicts among the multiple processes and threads attempting to log events.

You could choose either a .NET-based or Java-based logging package as the single logging package to be used from both .NET and Java. This example uses the Java-based package log4J to do the logging, but accesses the log from both sides, to demonstrate how transparently .NET can use existing Java classes.

The goal is to create a simple application containing both Java and .NET classes, where both the Java and .NET classes use the Java-based log4J logging package. The application has a .NET-based Windows Forms GUI, which calls the Java classes that perform the logging operations.

In the remainder of this article, you’ll walk through the process of setting up the interoperability project, creating the proxies, and building and running the project.

Requirements

To complete the project, you’ll need Microsoft Visual Studio .NET 2003 and the .NET Framework 1.1 installed on your machine. You can get the project to build using the .NET Framework SDK or Visual Studio .NET 2002, and .NET Framework 1.0, but you will need to make some modifications outside the scope of this article. The JNBridgePro documentation contains some suggestions on how you can proceed with older versions of .NET.

On the Java side, you must have a Java Development Kit (JDK) installed on your machine. You may use any JDK of version 1.2.2 or later. You can download a free JDK from Sun’s Java site.

Setting up

To set up the project, download the zip file containing the project code and unpack it. The zip file contains two sub-folders, Project and Completed. The Project folder contains all the code needed to create the project. The Completed folder contains the completed, ready-to-run, project, in case you don’t want to create the project yourself.

The Project folder contains dotNet and Java folders containing the .NET and Java portions of the project code, respectively. The Java folder contains a single Java class named JavaClass, which exposes a recordEvent() method that logs a supplied message to a specific logging category, as shown below:
package devX.logging; import org.apache.log4j.*; public class JavaClass { private static Category cat = Category.getInstance(“JavaClass”); public void recordEvent(String message) { cat.debug(message); } }

Although you’ll find the source file in the accompanying code, JavaClass is already compiled, so you need do nothing else to it.

In addition to Java code, the Project folder contains two .NET C# source code files. Form1.cs defines a Windows application that calls both .NET and Java objects, each of which logs events through the log4j Java-based logging package. The DotNetClass.cs file defines a .NET class similar to the JavaClass mentioned above. The DotNetClass also contains a recordEvent() method that logs a supplied message to a specific logging category:

 using System; using org.apache.log4j; namespace LogDemo { /// <summary> /// Sample .NET class that calls log4j. /// </summary> public class DotNetClass { private static Category cat = Category.getInstance("DotNetClass"); public DotNetClass() { } public void recordEvent(String message) { cat.debug(new java.lang.JavaString(message)) } } } 

Category is a .NET class that acts as a proxy for the corresponding Java Category class in the log4j package. .NET code accesses Java classes and objects by interacting with the corresponding proxy object. You’ll see more about proxies and how they’re generated and used in the remainder of this article.

The Completed folder contains everything in the Project folder plus additional files that allow the project to run without additional changes.

In addition to the project code, download the logging package log4j and unpack it in a location of your choice.

Finally, you’ll need JNBridgePro from the JNBridge Web site. For the purposes of this project, you may download either the EE or SE version. JNBridge provides 15 days of free use from the time that you install JNBridgePro; which should be sufficient to complete this project.

Install JNBridgePro by double-clicking on the downloaded installation file and following the instructions. Make sure that JNBridgePro is set up correctly by launching the JNBProxy proxy generation tool (through the Start menu or by double-clicking on the desktop icon). The first time you do this, you’ll see a dialog box that allows you to specify the Java configuration (see Figure 1). Make sure to check the “Start Java automatically” checkbox and specify a valid path is specified in the “Locate the java.exe file …” text box. After doing so, click the OK button. You can close JNBProxy at this point, or you can leave it open and proceed to the next step.

Figure 1. Specifying Java’s location: Use this dialog, displayed by the JNBProxy proxy generation tool, to specify that you want to start the Java side automatically and to specify the location of the java.exe file you want to use.

Generating Proxies
.NET classes communicate with Java classes through proxy classes. JNBridgePro generates a .NET proxy class for each Java class that you want to access from .NET. The .NET code then interacts with the proxy class, which manages the communication with the corresponding Java class. When you need an instance of a Java class, the .NET code automatically and transparently creates an instance of both the proxy and the corresponding Java object. To call a method on that Java object, you simply call the corresponding method on the proxy object. Similarly, to call a static method, you call the corresponding method on the proxy class, and to access a field in the Java object or class, you access the corresponding field on the proxy object or class.

The JNBProxy proxy generation tool creates these proxies and collects them in a .NET assembly, which appears as a DLL file that is linked into the .NET project.

To create the proxy assembly, launch the JNBProxy proxy generation tool (if it hasn’t already been launched in the previous section). Specify the locations of the Java class and jar files containing the classes for which proxies will be generated by selecting the Project, Edit Classpath… menu item, and then navigating to the Project\Java folder, which contains the devX.logging.JavaClass class file, and the file log4j-1.2.8.jar from the unpacked log4j zip file. Click on the OK button when you’re done.

Next, load the classes for which you wish to generate proxies into the proxy generation tool. First, select the Project, Add Classes from Classpath… menu item, and then type in the class name “devX.logging.JavaClass.” Make sure to check the “Include supporting classes” checkbox. Checking that option causes JNBProxy to generate proxies for all the classes that you might possibly need when accessing JavaClass. Click on the Add button, then on the OK button. JNBProxy will load approximately 200 classes. Repeat the process to load the logging classes in the log4j-1.2.8.jar file. JNBProxy will load a second set of classes.

You’ll want to generate proxies for all the classes you’ve loaded, so select the Edit, Check All in Environment menu item. Finally, select the Project, Build… menu item, navigate to the Project\DotNet folder, and enter the file name loggingProxies to generate a file named loggingProxies.dll containing the proxy classes. Figure 2 shows how the JNBProxy window looks after building the proxies. Note that you may get a warning message that some possibly required classes are missing. You can ignore this message, because these classes are necessary only if you want to log to other destinations, such as a JMS publisher—and you won’t be doing that in this project.

Figure 2. Generating Proxies: Here’s how the JNBProxy window looks after generating the proxy assembly.

Setting Up the .NET Program
Double-click on the Project\DotNet\LogDemo.sln file to open the .NET project. Before building the project, add the proxies to the project by adding a reference to the assembly loggingProxies.dll that you created in the preceding section. You also need a reference to the assembly jnbshare.dll that you’ll find in the JNBridgePro installation folder. Jnbshare.dll contains the core JNBridgePro functionality used to manage communications with the Java classes. After adding the references, you should be able to build the project without errors.

Figure 3. Starting the Binary Server: Here’s an example of the command line to start the Java side. Note that your paths may differ from the ones shown here.

To finish setting up the .NET program, copy the file jnbproxy.config from Project\DotNet into your build folder, which will either be bin\release or bin\debug, depending on your Visual Studio project build settings. jnbproxy.config contains configuration information that tells the .NET side where the Java code is located and which protocol will be used to communicate with it. In this case, jnbproxy.config specifies that the Java code is located on the same machine as the .NET code, that it will listen on port 8085, and will communicate with the binary protocol.

Running the Program

If you examine Form1.cs, you’ll see that it uses the BasicConfigurator class, which for demonstration purposes causes logged messages to appear in the Java console window. Note that it’s quite possible to log to files, JMS publishers, or other endpoints.

Before starting the .NET program, you’ll need to start the JVM containing the Java classes, so they’ll be able to receive the requests from the .NET side. Do this by opening a command-line window and typing in the following command line:

 java --cp <path to Project\Java>;<path to jnbcore.jar in JNBridgePro installation folder>;<path to log4j- 1.2.8.jar> com.jnbridge.jnbcore.JNBMain /props <path to jnbcore_tcp.properties in JNBridgePro installation folder> 

To be safe, surround each of the paths in the preceding command line with quotes, because they may contain spaces. The jnbcore.jar file contains the core JNBridgePro functionality that allows Java classes to communicate with the .NET side. The jnbcore_tcp.properties file contains configuration information that tells Java which communications protocol to use and which port to listen on for requests. The sample project uses the binary protocol and listens on port 8085. Figure 3 shows what you will see if all goes well.

Figure 4. The Logging Application: The figure shows the .NET front-end application that lets you log messages from either .NET or Java.

Next, start the .NET program from Visual Studio .NET, or simply by double-clicking on LogDemo.exe. Figure 4 shows the running application.

Clicking on the “Log .NET event” button causes the DotNetClass to log an event from .NET. Click on the “Log Java event” button to cause JavaClass to log an event from Java. You can either supply a custom message to log or just use the supplied defaults. In each case, the Java-based log4j package performs the logging operation, and displays the logged messages in the console window, as shown in Figure 5.

In this project you’ve seen how to log messages from both .NET and Java code into a common logging package—in this case running on the Java platform. Using a common logging package consolidates .NET-originated and Java-originated logging messages in the same console window or file, and lets you easily see the sequence of from both the .NET and Java sides.

Figure 5. Logged Messages in the Console: Here’s how the logged messages appear in the console window.

More generally, you’ve seen how call to Java classes directly from .NET by using a runtime bridge. In the sample application, .NET code calls Java classes in the log4j package, and also calls the Java class JavaClass. You can easily extend this technique of directly accessing Java classes from .NET to other Java class libraries, and you can also use it to let .NET classes access EJBs, JMS queues, or other Java and J2EE capabilities. Using a runtime bridge is simple, transparent, and extensible, because your .NET code accesses the Java code through proxies, and has no idea that it’s talking to Java classes.


Advertisements

30 responses to this post.

  1. Posted by Nakshtra Choudhary on March 9, 2012 at 4:49 pm

    hummmm, is it possible ?? that we are calling a java class from .net program ?

  2. Posted by Denno Secqtinstien on March 9, 2012 at 4:50 pm

    yes it is possible in .net ?

  3. You are my inspiration , I possess few blogs and infrequently run out from to post .

  4. Hello Webmaster, I noticed that https://dennosecqtinstien.wordpress.com/2012/02/22/calling-java-classes-directly-from-net/ is ranking pretty low on Google and has a low Google PageRank. Now the Google PageRank is how Google is able to see how relevant your webpage is compared to all the other webpages online, if you cannot rank high at the top of Google, then you will NOT get the traffic you need. Now usually trying to get to the top of Google costs hundreds if not thousands of dollars and very highly optimized targeted marketing campaigns that takes a team of experts months to achieve. However, we can show you how to get to the top of Google with no out of pocket expenses (free traffic), no stupid ninja tricks, no silly mind control techniques, and this will be all white hat with no blackhat software or tactics that could possibly land you on bad terms with Google and put you in the dreaded “Google Sandbox”. We’ll show you how to easily capture all the targeted traffic you need, for free, multiple ways to land fast (not months) first-page rankings in Google and other major search engines (Bing, Yahoo, Ask, etc), even show you strategies on how to earn daily commissions just try Ranking Top of Google, please check out our 5 minute video.

  5. Regularly have a look at your current personal computer’s total program. I prefer to operate reads immediately since they decrease your personal computer and may consider some time. If perhaps section of your personal machine method definitely seems to be contaminated, you’ll be able to check out the particular believe portion merely. If you’re by using a free plan, make sure that that removes the actual adware and spyware it’s got discovered. Many of these free of charge packages may identify the particular dangers but ask you to purchase the put in get correctly to eliminate the infection. I think these specific packages should be deleted as well as swapped out by simply programs which have entire functionality.

  6. I’m just writing to make you understand what a remarkable experience my princess found reading through the blog. She picked up too many details, which included what it’s like to have an excellent helping spirit to let the others really easily gain knowledge of certain extremely tough topics. You truly surpassed my expectations. Thank you for providing such priceless, dependable, explanatory and in addition unique thoughts on this topic to Emily.

  7. My brother recommended I might like this website. He was totally right. This post actually made my day. You can not imagine simply how much time I had spent for this information! Thanks!

  8. This design is spectacular! You definitely know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Excellent job. I really loved what you had to say, and more than that, how you presented it. Too cool!

  9. Very interesting information!Perfect just what I was looking for!

  10. Wow, incredible blog format! How long have you ever been blogging for? you made running a blog glance easy. The total glance of your website is magnificent, let alone the content!

  11. Greeting from over the world. informative article I must return for more.

  12. I every time download a full show in parts, that’s always existing at YouTube, for the reason that my network connection is very slow and YouTube fulfils my desires.

  13. Web hosting getting cheaper with offering good functionalities.I have tried some Awesome web hosting providers and found them great

  14. Hi my loved one! I want to say that this article is awesome, nice written and come with approximately all significant infos. I would like to look extra posts like this .

  15. I’m really impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you customize it yourself? Either way keep up the excellent quality writing, it is rare to see a great blog like this one today..

  16. Was wondering if there was any wordpress photo portfolio similar to links below.

  17. Good report, but noooooo not OsCommerce! I dose on tylenol when using OSCommerce so I can avoid the migranes. Check out Interspire, it’s what I have been using lately and it’s like a lighter edition of magento.

  18. I believe one of your advertisements caused my web browser to resize, you may well want to put that on your blacklist.

  19. Please message me with any pointers on how you made your website look this awesome, I would be thankful!

  20. Jesus Christ there is a lot of spammy comments on this site. Have you ever before believed about attempting to get rid of them or installing a tool?

  21. An interesting blog post there mate ! Thanks for the post !

  22. As soon as I originally commented I clicked on the Notify me when new comments are added checkbox and currently each and every time a remark is added I receive four emails with the identical comment.

  23. Even though I really like this publish, I believe there was an spelling error shut towards the finish of the 3rd section.

  24. I’ve been browsing on-line greater than 3 hours lately, but I by no means discovered any attention-grabbing article like yours. It¡¦s pretty value sufficient for me. In my opinion, if all website owners and bloggers made good content material as you probably did, the web will likely be much more helpful than ever before.

  25. Amazing article, thanks, I will subscribe to you RSS later!

  26. Weird , this post shows up with a dark color to it, what shade is the primary color on your web-site?

  27. Re: Whoever made the remark that this was a great internet site truly needs to possess their head evaluated.

  28. Hey there, I just hopped over to your web-site thru StumbleUpon. Not somthing I would typically browse, but I appreciated your views none the less. Thanks for creating something worthy of reading.

  29. Just discovered this site through Google, what a pleasant shock!

  30. Do youve a spam concern on this web site; I also am a blogger, and I was questioning your scenario; we have made some good techniques and we are looking to exchange options with other people, be certain to shoot me an e-mail if interested.

Comments are closed.

%d bloggers like this: