Share this page 

Wrap a Java class in a COM object (this howto is deprecated)Tag(s): DEPRECATED


Use the Microsoft javareg utility to register a java class as a COM server. Once registered, the Java class will be visible from all languages that can deal with COM objects. I am giving here some examples in VbScript, JScript, ASP and Powerbuilder.

NOTE: The class can compiled with any JDK but the actual execution will use the Microsoft JVM installed on the system.

The javareg utility is part of the Microsoft Java SDK which can be freely downloaded from the Microsoft Web site.

First a simple Java class.

[JavaSays.java]

package JavaCom; 
 public class JavaSays { 
   public String Hello() {
    return "Hello world" ;   
   }
   public String Say(String what) {
    return what ;   
   }
}
Then this BAT file is executed to register our class.
javareg /register /class:JavaCom.JavaSays /progid:JavaCom.JavaSays
md c:\Windows\Java\TrustLib\JavaCom
copy JavaSays.class c:\windows\java\trustlib\javacom
That's it. The system now has a COM object called JavaCom.JavaSays installed.

VbScript and JScript are useful scripting tools. They are now part of a regular Windows installation (or IE). If your Windows installation is too old, you can download the Windows Scripting Host from the Microsoft Web site.

[VbScript TestJavaCom.vbs]

'  VBSCRIPT  connect to a Java COM object
Dim objJava
Set objJava = WScript.CreateObject("JavaCom.JavaSays")

strFromJava = objJava.Hello
MsgBox strFromJava, _
       0,    _
       "JAVA COM OUTPUT"

strFromJava = objJava.Say("Displayed by VbScript via a Java object")
MsgBox strFromJava, _
       0,    _
"JAVA COM OUTPUT"

[JScript TestJavaCom.js]

// JSCRIPT  connect to a Java COM object
var objJava = WScript.CreateObject("JavaCom.JavaSays")
var WSHShell = WScript.CreateObject("WScript.Shell");

strFromJava = objJava.Hello()
WSHShell.Popup(strFromJava,
               0,
               "JAVA COM OUTPUT",
               0 );

strFromJava = objJava.Say("Displayed by JScript via a Java object")
WSHShell.Popup(strFromJava, 0, "JAVA COM OUTPUT", 0 );

[ASP TestJavaCom.asp]

<% 
  Set objJava = Server.CreateObject("JavaCom.JavaSays") 
%> 
<BR>
test 1 : <% =objJava.Hello() %><BR>
test 2 : <% =objJava.Say("From ASP via a Java Object") %>

[PowerBuilder]

OLEObject objJava
string strFromjava

objJava = CREATE OLEObject
objJava.ConnectToNewObject("JavaCom.JavaSays")

strFromJava = objJava.Hello()
MessageBox("From PB via JavaCom", strFromJava)

strFromJava = objJava.Say("Displayed by PB via a Java object")
MessageBox("From PB via JavaCom", strFromJava)

DESTROY objjava

See also Sun's Javabeans bridge for ActiveX.