[Previous] [Contents] [Next]

The Java Moniker

The Microsoft Java VM offers its own special moniker called the Java moniker. Java monikers are identified by a string name in the form java:myclass.class, where java is a registered ProgID that refers to the CLSID of Microsoft's Java VM. The Java moniker enables an application written in any language to access Java code via MkParseDisplayName. In Visual Basic, you can access Java code using the syntax GetObject("java:myclass.class"). The following Visual Basic code fragment uses the Date class implemented as part of the java.util package:

Private Sub Command1_Click()
    Dim x As Object
    Set x = GetObject("java:java.util.Date")
    MsgBox x.toString() ' Displays current date and time
End Sub

Using the same syntax, you can access methods of a custom-built Java class. The following code shows a Java class:

//
//
// SumClass
//
//
public class SumClass
{
    public int Sum(int x, int y)
    {
        return x + y;
    }
}

In Chapter 3, we exposed the SumClass class as a coclass by generating coclass wrappers for the Java class and using Visual J++ to build a type library. To avoid this drudgery, we could have simply used the Java moniker to access SumClass, as shown here:

Private Sub Command1_Click()
    Dim x As Object
    Set x = GetObject("java:SumClass")
    MsgBox x.Sum(5, 3)
End Sub