Java Access to COM Objects

In Chapter 5, I demonstrated how the Java Type Library Wizard creates a set of Java classes for an ActiveX control. But that’s only part of the story; the wizard can, in fact, prepare any COM-compliant class for use in Java. Remember, COM is a basic communications standard that applies to a wide variety of software components. It applies not only to ActiveX but also to other software components. A dynamic-link library, for example, might expose some or all of its functionality through COM interfaces.

Here’s an example: Let’s say that you have a dynamic-link library named UtilityCOM.dll, which supports two interfaces, IMath and IUseStates. Assuming that UtilityCOM was registered during its installation, you’ll be able to use the Java Type Library Wizard to extract interface information and build Java classes. The summary.txt output from the wizard might look like the following.

public class utilitycom/CUtilityCOM extends java.lang.Object
{
}

public interface utilitycom/IMath extends 
    com.ms.com.IUnknown
{
    public abstract int addInts(int, int);
    public abstract int powInt(int, int);
}

public interface utilitycom/IUseStates extends 
    com.ms.com.IUnknown
{
    public abstract int getState();
    public abstract void setState(int);
}

The first class listed, CUtilityCOM, is the one you use to create objects of this class. But notice that the implementation of CUtilityCOM is empty. This should remind you of an important distinction of COM programming in Java: You never directly access COM objects. All interaction with a COM object takes place through an interface, as I’ll show you in a moment.

To import the UtilityCOM classes, you’ll need to include this statement at the beginning of your Java source file.

import UtilityCOM.*;

You can also import specific interfaces and classes using statements such as these.

import UtilityCOM.CUtilityCOM;
import UtilityCOM.IMath;

To create a UtilityCOM object, you use the standard Java syntax for allocating a class object, casting the result to an appropriate interface.

IMath util = (IMath)new CUtilityCOM();

int n = util.addInts(2, 2);

If you’ve done any COM programming in C++, you’ll see an immediate advantage to Java: It hides complexities, such as the CLSIDs that are used when CoCreateObject is called to build a new COM object. For the most part, using a COM object is just like using any Java object; the important difference is that you always communicate with the COM object through a reference to an interface, never through direct reference to the object itself. The following piece of code, for instance, would cause a run-time exception.

CUtilityCOM util = new CUtilityCOM();

© 1997 by Scott Ladd. All rights reserved.