RMI and Native Method Calls

RMI is a Java-only remote object scheme, so it doesn’t provide a direct connection between objects implemented in different languages, like CORBA does. But, using Java’s Native Interface API, it is possible to wrap existing C or C++ code with a Java interface and then export this interface remotely through RMI.

To demonstrate, let’s suppose we have some (legacy) native code that implements a service we want to export through RMI to remote clients. We can create an implementation of our Account interface that uses this native code to implement the doSomething( ) method on our remote interface. The implementation for a NativeAccountImpl is shown in Example 3-4. The only significant difference between this implementation and our original AccountImpl is that the doSomething( ) method is declared native, so the method body is left empty.

Example 3-4. Remote Object Using a Native Method Implementation

import java.rmi.server.UnicastRemoteObject; import java.rmi.RemoteException; import java.util.List; import java.util.ListIterator; /** * NativeAccountImpl: Implementation of the Account remote interface using * JNI native methods for the account transactions. */ public class NativeAccountImpl extends UnicastRemoteObject implements Account { // Our current balance private float mBalance = 0; // Name on account private String mName = ""; // Create a new account with the given name public NativeAccountImpl(String name) throws RemoteException { mName = name; } public ...

Get Java Enterprise in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.