The following example shows how to use COM objects in Java code. Suppose comserver.dll, which defines a CComBeeper class and an IComBeeper interface, is registered as having type library information. Running jactivex /javatlb on Comserver.dll creates a package named comserver, containing the Java class CComBeeper and the Java interface IComBeeper.
When you've run jactivex on comserver.dll, you can use the import statement in your Java source code to easily refer to classes in the comserver package. For example:
import comserver.*; // import comserver package
This statement is identical to Java's syntax for importing an entire package. It is not strictly necessary, however. In Java, any class can be referenced using its fully qualified name (for example, java.awt.Canvas), as long as that class name is found when searching the class path. The import statement allows you to refer to the class using its short name (for example, Canvas).
The same is true for importing COM classes. The import statement is not required to use the COM class. It simply allows the class to be referenced using its short name. Any COM class can always be referenced using its fully qualified name.
Instead of importing the entire package, you could explicitly import individual classes within a type library. To import individual classes, use the following syntax, which is identical to Java's syntax for importing a single class.
import comserver.IComBeeper; import comserver.CComBeeper;
The Java classes that wrap COM classes can be used the same way you use other Java classes. For example, the following code declares a reference of type IComBeeper, initializes it by creating an instance of the COM class CComBeeper, gets and sets the value of a property of the object, and then calls two methods on the object.
IComBeeper testBeep = (IComBeeper)new CComBeeper(); int myTone = testBeep.getSound(); testBeep.putSound(64); testBeep.Beep();
Because CComBeeper is a COM class, you must use one of its interfaces to manipulate an instance of the class. COM does not support accessing properties or methods on a class independently from its interfaces. For example, the following statements would be legal Java code, but will cause errors when used with a COM class.
CComBeeper testBeep = new CComBeeper(); // Don't do this with a COM class. int myTone = testBeep.getSound(); // Causes runtime errors with COM classes.
Caution An important restriction on using Java classes that wrap COM classes: an instance of the class cannot be directly used. Use the instance through an interface. However, if you generate the .java files by using the jactivex tool with its /javatlb /xi option, you can call methods on the object directly without first casting to an interface pointer. For more information on using the jactivex tool, see Jactivex.