Java Interface Library v2/en

From expecco Wiki (Version 2.x)
(Redirected from Java Interface Library v2)
Jump to navigation Jump to search


This article discusses version 2 of the Java Bridge. The article for version 1 (pre expecco 2.9) can be found here.

The Java Interface library ("Java Bridge") is used to interact with Java objects inside an external Java Virtual Machine (JVM).

The access to Java objects, classes and programs is done via a framework called "Java-Bridge", which is similar in operation to the dotNET bridge. This framework implements transparent forwarding of method (virtual function) calls to Java objects, which exist in a local or remote Java Virtual Machine (JVM). Also, return values, callBacks and exception information are passed back from the Java program to expecco. This is done by a proxy-object mechanism, which catches all function calls, wraps the arguments, sends a datagram to the other bridge side, awaits the reply and returns the result to the original caller. Thus, remote procedure calls are almost completely transparent to the Smalltalk/JavaScript code inside expecco. In your elementary code, you can write remote function calls as if they were to local objects.

Notice that this document describes the low level framework, which implements the bridge communication. A much easier to use high level interface (called "Groovy Blocks") exists and should normally be used, if you need access to a Java application's internals during testing. Please take a look at "Groovy Block API" and "Testing Java Applications using Groovy blocks".


On the expecco side, the bridge consists of a number of Proxy objects, which behave like regular Smalltalk objects as seen from elementary expecco code. However, instead of performing an action when one of their methods (virtual functions) is called, they send a message over a socket connection to the Java VM (actually: to a bridge software inside the Java application) which decodes the message and sends it to the destination Java object. The same is done in reverse direction with the return value.

+---------------------+     +----------+     +----------------+      +----------------+     +---------+
|                     |     |          |     |                |      |                |     |   Java  |
|       expecco       |---->|  Proxy   |---->|      Bridge    |==>>==|      Bridge    |---->|  Object |
|  (elementary code)  |<----|          |<----| (expecco side) |==<<==|   (Java side)  |<----|         |
+---------------------+     +----------+     +----------------+      +----------------+     +---------+

This setup allows for transparent communication with objects inside a local or remote Java VM. This may be either utility functions which happen to be convenient for the test application (for example: file parsing, syntax analysis, protocol implementations or access to specific hardware via driver libraries), or the tested application in the system under test itself.

Especially, it allows for the objects of the tested application to be looked into, manipulated and for functions of it or underlying frameworks to be called.

For expecco code, we tried to make this as transparent as possible, however there are a few exceptions, when function names need to be translated (for example, because the function naming syntax is different) or due to the fact that for some operations no corresponding name exists in Smalltalk (array access, for example).

Of course, multiple such connections can coexist and be served/handled in parallel. This enables an expecco test suite to communicate with both sides of a tested client-server Java application, for example.

Notice that a similar mechanism is used in expecco to communicate with .NET, Qt (C++) and C applications.

Activating the new Java Bridge[edit]

The bridge framework has been reworked completely recently. While version1 used multiple socket connections, the new version2 protocol multiplexes all communication over a single connection, thus simplifying firewall setup. The two bridges use incompatible wire protocols, whereas code wise, the two versions should behave equivalent. However the new bridge supports a few new features, such as future values.

By default, the version2 bridge is now used in expecco. If, for whichever reason you need to use the old bridge, you can switch back via the settings dialog (e.g. if you have an old JavaBridge installed on a target).

To deactivate the new bridge in expecco, navigate to ExtrasSettingsPluginsJava Bridge and uncheck the Use new Bridge (experimental) checkbox:


Attention: Toggling the checkbox will terminate all currently active Bridge connections due to incompatibilities between the new and the old versions' wire protocols.

Initializing / Releasing the Bridge[edit]

Before any communication can take place between expecco and any Java object, the Java side of the bridge has to be started, and a communication has to be established. In expecco, all of the bridge classes are found in the JAVA namespace.

The main interface class is "Java", in the "JAVA" namespace.

Start and Connect to a JVM on the Local Machine[edit]

To start the Java-side of the bridge (actually executes java as a background command) on the local machine, and to establish a connection to that JVM, use:

    java := JAVA::Java newWithServer.

or (in JavaScript):

    java = JAVA::Java.newWithServer();

The bridge connection should be closed, if the bridge is no longer needed. Release the bridge with:


which terminates the connection.

Start and Connect to a JVM on a Remote Machine[edit]

The above code snippet starts a new Java VM on the local machine and connects to it. Alternatively, you may want to connect to an already running Java program (typically, your system under test). In order for your program to be reachable, it must allow for the bridge to connect to it via a special bridge-connection, which is a socket connection. For this, it must execute the server code found in the "JavaBridge.jar" file. To pass parameters you will typically start it from a command line or a little shell/batch script.

Call (on the shell/cmd level):


The "JavaBridge.jar" file is found in the installation directory of expecco at:


The Java Bridge code allows for either side to initiate the connection - i.e. it can be run in server mode, where it awaits an incoming connection, or in client mode, where it actively initiates a connection. After connection establishment, there is no difference in the operation of the bridge. However, depending on the setup of your network infrastructure, especially firewalls and security considerations, either mechanism may be easier to be used.

Assuming that the bridge is already running on the remote machine as server (default), use "newConnectedTo:port:withTimeout:" to connect to it from the expecco side:

   java := JAVA::Java newConnectedTo:'myHost' port:4567 withTimeout:30.

This will initiate the connection setup from the expecco side.

Alternatively, if started in client mode use "newWaitingForConnectOnHost:port:withTimeout:":

   java := JAVA::Java newWaitingForConnectOnHost:'localhost' port:4567 withTimeout:30.

which will open a port on the expecco side, and wait until the Java side connects to it. For more details see API

Startup Parameters[edit]

You can use any parameter in any order. If no parameter is used then the bridge listens on port 14014 in server mode without keepAlive.


 Shows the help

-ip <aHostnameOrIP>

 In client mode this specifies the IP address or the hostname to connect to. In server mode this specifies the IP address or the hostname to bind to.

-port <aPortNumber>

 In client mode this specifies the port to connect to. In server mode this specifies the listening port.


 The bridge will start in client mode. If not set the bridge is started in server mode.


 By setting this flag the bridge will not exit after the connection has closed and starts to connect or listen again. Otherwise, it will run for a single connection session only.

Loading Applications (from the expecco side)[edit]

Normally, you would start your application with the required command line arguments and include the Java Bridge as jar there. However, in some situations, it may be required to dynamically load other jars into the connected Java VM. By accessing a classloader, additional classes, or applications as contained in JAR files can be loaded from the expecco side.

This can be used to add a JAR file to the classloader:

    java loadJarByPath:'pathToJarFile'. "/ assuming "java" is a handle as returned from the above connect

or, if the JAR file is loaded in memory:

    java loadJar:jarByteArray. "/ where "jarByteArray" is a ByteArray containing the JAR file

If the JVM is on a remote machine, the path is resolved on the expecco side and the JAR will be transferred to the remote side.

Should transferring the JAR be too much overhead, an additional mechanism is provided:

    java loadExtension:'pathToJarFile'.

this will cache the JAR file on the bridge side and eliminate the overhead of subsequent invocations.

Java Class Access[edit]

This following code sample simply references (i.e. accesses) the class "JFrame" from the "javax.swing" package. The fully specified class name in Java would be "javax.swing.JFrame":

    jFrameClass := java getJavaClass:'javax.swing.JFrame'

there is also a shortcut message "@", which performs the same operation:

    jFrameClass := java @ 'javax.swing.JFrame'

Or, if you want to load multiple classes:

        do:[:jFrame :jButton | 
            "do something with JButton and JFrame" 

the above ensures that the classes are loaded and invokes the code inside the block with the resolved class objects as arguments. From 1 to 10 import names can be given as "import:" argument.

The v2 bridge also supports dynamic compilation of Java source code:

    java getJavaClass:'className' fromSource:'classSource'. "/ where classSource is a String containing valid Java source code

and loading precompiled Java bytecode:

    java getJavaClass:'className' fromByteCode:byteCode. "/ where byteCode is a ByteArray containing valid Java bytecode

for details see Remote Dynamic Code Injection

Instantiating a Class[edit]

Object instances are created via the "new"-message, sent to a proxy of a Java class. You can get this proxy as described in the previous section. For example, if we want to create a new instance of a "JFrame" and a "JButton", write:

    frame := (java getJavaClass:'javax.swing.JFrame') new.
    button := (java getJavaClass:'javax.swing.JButton') new.


    frame := (java @ 'javax.swing.JFrame') new.
    button := (java @ 'javax.swing.JButton') new.

The first statement results in a proxy object for a new "JFrame" instance. The second line results in a proxy for a new "JButton" object.

Calling Instance Methods[edit]

A method call is done by a message send to a proxy object, where the message is the method name to call. For example, to call the "setVisible(boolean isVisible)" method on the above JFrame object, we send the following message to that proxy:

    frame setVisible:true.

As method naming is different in Smalltalk and Java, a dynamic translation is applied when sending messages from Smalltalk code to a remote Java object. Smalltalk has arguments embedded inside parts of a so called "keyword" message, such as in "receiver foo:arg1 bar:arg2", where "foo:bar:" would be the message name, and "arg1", "arg2" be the arguments.

In Java, the message name is a single identifier, and arguments are written in an argument list after the message name; eg: "receiver.fooBar(arg1, arg2)".

When message names are translated, only the very first part of the Smalltalk keyword message is taken ("foo" in the above example), and the remaining parts are simply ignored. Thus, any of the Smalltalk messages "foo:bar:", "foo:xxxx:" and "foo:_:" (a single underscore as second part) all translate to the same Java message name "foo()".

Therefore, to call a method with more than one argument, like "setSize(int width,int height)" on a JFrame instance we can write:

    frame setSize:300 _:200.

but just as well:

    frame setSize:300 anyWord:200.

or any other selector with "setSize:" as its first component. The selector translation mechanism simply takes the first part as the Java selector.

In practice, you should take a reasonably descriptive name, such as: "frame setSize:300 height:200" or only the Java name as first part, such as "frame setSize:300 _:200".

For a call of a method with 4 arguments, we could write:

    frame setBounds:100 y:50 width:300 height:200.


    frame setBounds:100 _:50 _:300 _:200.

Also here the "y: width: height:" can be named as you want, but the first part must be "setBounds:".

Calling Static Methods[edit]

Calling a static method on an object is not different from calling non static methods. In most cases you will call a static method not on an object but directly on the class. This is done by using the class object as "receiver" of the message. For example, if we want to call the static method "isDefaultLookAndFeelDecorated()" of the JFrame class, write:

    (java @ 'javax.swing.JFrame') isDefaultLookAndFeelDecorated.

Accessing Fields[edit]

As Smalltalk does not support access of an object's fields from the outside (it is fully encapsulated, and access from outside is ONLY allowed via getters/setters), an additional translation mechanism is provided for field access.

Accessing a field of a Java object or a class's static field uses the same syntax as method calls. To access a field, send a message where the message is the field name. To access the field of a class the field must be static. For example, to get the value of the static field named "EXIT_ON_CLOSE" of the "JFrame" class, write

    value := (java getJavaClass:'javax.swing.JFrame') EXIT_ON_CLOSE.

The variable "value" now holds the integer value of the "EXIT_ON_CLOSE" constant.

Assuming that a "JFrame" object had a field named "myField", to access this field, we'd have to write:

    value := frame myField.

and "value" now holding whatever "myField" returns. This could be another object reference or any primitive value.

Setting Fields[edit]

To set a field, use a setter-like method call:

    frame myField: newValue.

Name Conflicts[edit]

In very rare situations, a Java object may contain both a field and a method by the same name. In this case, the Smalltalk code cannot depend on the dynamic translation mechanism (which actually looks for either a field or method name to match), but instead make it explicit, which operation is wanted: Use:

    frame getFieldByName:'myField'

to read a field, and:

    frame setFieldByName:'myField' value:123.

to write the field.

If there are both fields and methods by the same name, and you use the non-explicit call, the bridge will always assume that you want to call the getter/setter and perform a method call.


Passing Smalltalk Collections to Java[edit]

Smalltalk collections can now be directly passed to Java with a few limitations:

  • The identity of the Smalltalk collections will not be preserved. passing the same collection to Java multiple times will result in multiple instances of the same array on the Java side. (to bypass this instantiate a new Java array)
  • Smalltalk collections need to be explicitly converted to the correct type (e.g. a SignedIntegerArray on the Smalltalk side matches an int-Array on the Java side)

Instantiating Arrays[edit]

The new bridge supports instantiation of arrays (whereas previously reflection had to be used to instantiate arrays from the Smalltalk side). There are two ways an array can be instantiated:

    intArray := (java getJavaClass:'int[]') new:#[ 1 2 3 4 5 ] asSignedIntegerArray. "/ instantiates a new array of type "int" with the contents "1, 2, 3, 4, 5"
    intArray := (java getJavaClass:'int[]') new:10. "/ instantiates a new empty array of type "int" with 10 elements.

Accessing Arrays[edit]

To achieve better performance, arrays of primitive types smaller than a certain size have their contents cached on the Smalltalk side:

    intArray contents at:1. "/ this will access the first element of the cached contents.

large arrays are not serialized immediately. large arrays will be serialized when contents is called the first time.

Attention: Java arrays are not immutable. changes to an array are not reflected in the cached contents. if an array has been updated, call refresh on the array to update the cache. arrays will not be updated automatically.

    shortArray := (java getJavaClass:'short[]') new:10. "/ new empty "short" array with 10 elements

    "/ copy the contents of the Smalltalk collection to the newly instantiated short array
    (java getJavaClass:'java.lang.System') arraycopy:(#[ 1 2 3 ] asSignedWordArray) srcPos:0 dest:shortArray destPos:0 length:3.

    shortArray at:0. "/ will reflect the changes made to the array

    shortArray contents at:1. "/ will still return 0 because the cached contents have not been updated.

    shortArray refresh. "/ update the cached contents

    shortArray contents at:1. "/ will now correctly reflect the changes made to the array

Boxed Primitives[edit]

In version 1 of the Java Bridge boxed primitives were unboxed automatically and the identity was not preserved. In version 2 a mechanism is provided allowing to preserve the identity of boxed primitives: boxedDo:aBlock .


    java boxedDo:[
        boxedInt := java getJavaClass:'java.lang.Integer' new:30. "/ instantiate a new boxed integer. boxedInt now holds a reference to this object
    intValue := boxedInt value. "/ extract the value of the boxed integer. (no overhead)

Asynchronous Communication[edit]

In the new Bridge, everything can be done asynchronously. This is achieved via the asyncDo:aBlock method. Every request sent to the Bridge inside of aBlock will immediately return a lazy value. This lazy value will block upon access until the actual result is received from the Java side. The order of execution is guaranteed to be the same on the Java side as on the Smalltalk side.


    java asyncDo:[
        lazyInteger := (java getJavaClass:'java.lang.Integer') new:40. "/ this will return immediately
    actualInteger := lazyInteger value. "/ this will block until the result is available

Callbacks from Java[edit]

Sometimes you may want to execute a piece of Smalltalk code during the execution of the Java code. For example, we may want to install a Smalltalk observer to be notified when a button on a Java GUI was pressed, or some other callback from a Java framework.

The following code registers a Smalltalk block as a callback for a mouse press event of a button:

    listener := MouseListener new.
    listener implementMethod:'mousePressed' as:[ Transcript showCR:'Hello from Java' ].

The above creates the callback and the listener, which can now be registered on a button:

    button addMouseListener:listener.

Now, with the press of the button in the Java GUI, the Smalltalk block will be executed and writes "Hello from Java" to the Smalltalk console. Of course, any other (Smalltalk-)action code can be made to run via this mechanism.

But be aware, that the callback is possibly called later (when the elementary action, which installed the code, has already finished long ago). Also, as the Java code execution is not synchronized with any of your expecco action execution, the callback may also be called at any arbitrary time, even at times when no activity at all is executed on the expecco side. If you forget to cleanup, and the Java object is still alive, it may even be called after you have finished your test run (if you keep the Java Bridge handle around and alive, for example in an expecco environment variable).

So the Smalltalk callback code should not depend on any particular elementary action to be currently running, but instead in most cases write some information into a shared data container, preferably an instance of "SharedQueue", which is thread safe. Then, some other action (an elementary action) would read-wait and read events from that shared queue.

make sure that your test correctly cleans up any such callbacks afterwards. As a last resort, use the "Shutdown Bridge Connection" menu item, which closes the bridge connection, and thereby - as a side effect - removes any leftover callbacks. It does close the connection, and any remaining Java proxy object handles become invalid, though.

Another example, using an observer could look like:

    observer := java Observer new.
    observer implementMethod:'update'
        as:[:sourceObservable :argument|
            argument notNil ifTrue:[ Transcript showCR:('I was notified with: ',argument toString) ]
            ifFalse:[ Transcript showCR:'I was notified and the argument was nil' ].
    myObservable addObserver:observer.

When the observable calls "notifyObservers", the Smalltalk block will be executed.

Exceptions in Java[edit]

Exceptions on the Java side are signalled back to the Smalltalk side and raise a corresponding exception there. However, on the Java side, the call stack which lead to the exception has already been unwound at that time (Java exceptions are not proceedable). So a proceed in the Smalltalk-side exception handler only affects the Smalltalk caller, but may leave the Java side in an undefined state.

Remote Dynamic Code Injection[edit]

Sometimes we might want to execute code without the overhead of many rpc-messages being sent over the bridge, especially if we want to do something time critical, or want to make execution time measurements. For this, it is possible to load a class at runtime into the Java VM. The code of the class will first be sent to the Java VM, which will compile and load the generated byte code. Then, the class can be accessed via the bridge just like any other preloaded class.

The following example specifies the class code in a Smalltalk string and inject the code into the Java VM. Then an instance of that new class will be instantiated and finally a method of the object instance will be invoked:

   classCode := '
        package myPackage.test;

        import java.awt.BorderLayout;
        import java.awt.event.MouseAdapter;
        import java.awt.event.MouseEvent;
        import java.util.Calendar;

        import javax.swing.JButton;
        import javax.swing.JFrame;
        import javax.swing.JLabel;;

        public class MyInjectedClass {
            public void createSampleApp(){
                JFrame frame=new JFrame("Hello im injected");
                frame.setLayout(new BorderLayout());
                JButton button=new JButton("click me");
                final JLabel label=new JLabel("Text");
                button.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent e) {
                frame.setSize(300, 300);
    classObject := java getJavaClass:'myPackage.test.MyInjectedClass' fromSource:classCode.
    classObject new createSampleApp.

After the code has been injected, a new instance of "MyInjectedClass" is created and the "createSampleApp" method is called. Because the example implements a GUI, a Java window will open, containing a label and a button. Clicking the button displays the current time in the label.

Code Sources for Class injection[edit]

There are 3 possible types of class code sources which we can use to inject the code. In the examples before we directly used a simple "String" in the Smalltalk code as a code source. We also can use a "*.java" file as source. Just read the content of the file into a string and use it as in the previous examples.

To inject a "*.class" file use the following code:

java getJavaClass:'' fromByteCode:classCode.


This example creates a JFrame with one button inside. Then a MouseListener is created and registered on the button. When the button is pressed, the title of the window changes to "onPressed" and the Transcript shows the message "onPressed". When the button is released, the title of the window is changed to "onReleased" and the Transcript shows "onReleased". If the button lost the mouse focus, the bridge will exit (disconnect), and the Java side is terminated.

    |java frame button listener|

    "/getting a bridge
    java := JAVA::JavaBridge newWithServer.

    "/creating a new frame and button object
    frame := java getJavaClass:'javax.swing.JFrame' new.
    button := (java getJavaClass:'javax.swing.JButton') new:'Click'.

    "/creating a new mouse listener and adding callback blocks
    listener := (java getJavaClass:'java.awt.event.MouseListener') new.

    listener implementMethod:'mousePressed' as:[ Transcript showCR:'onPress'. frame setTitle:'onPressed' ].
    listener implementMethod:'mouseReleased' as:[ Transcript showCR:'onReleased'. frame setTitle:'onReleased' ].
    listener implementMethod:'mouseExited' as:[ Transcript showCR:'onExited'. java closeBridge. ].

    "/register the mouse listener on the button and make the frame with button visible
    button addMouseListener:listener.
    frame add:button.
    frame setSize:300 y:100.
    frame setVisible: true.

Differences between v1 and v2[edit]


  • A Java Bridge instance no longer requires multiple TCP ports to be open. This simplifies connection through ssh tunnels and firewalls.
  • The identity of strings and primitive wrappers can now be preserved. (see boxedDo)
  • Simplified instantiation and access of arrays. (see Arrays)
  • Every request to the Java side can now be done asynchronously. (see Asynchronous Communication)

Loading Applications[edit]

  • addJarByPath: and addToClassPath: are still supported but have been deprecated. use loadJar:, loadJarByPath: and loadExtension: instead. The new methods no longer require the jar or library to be present on the remote machine.

v1 v2

Java Class Access[edit]

  • Sending the fully qualified name with instances of "." replaced by "_" to the bridge handle is still supported, but not recommended.
  • A new method getJavaClass: has been introduced (also available for v1 since expecco v2.9). This solves the side effects of "_" being a legal character in class names.

v1 v2

Callbacks from Java[edit]

  • A new method implementMethod:as: has been introduced to assign callback blocks to method names. The old way is still supported.

v1 v2

Remote Dynamic Code Injection[edit]

  • Code injection was problematic in v1 and has now been re-implemented in v2.




class protocol[edit]

  • This will start a local Java VM, running the Java Bridge, and establishes a connection on a random free port.
A new connected instance of JAVA::Java class is returned.
  • This is the same as newWithServer but the path to the Java executable can be specified. The Java VM version must be 1.6 or higher to run the Java Bridge.
aJavaPathFilename - must be a instance of Filename
   Smalltalk: JAVA::Java newWithServerForJavaPath:('my\path\to\java.executable'asFilename).
   JavaScript: JAVA::Java.newWithServerForJavaPath("my\path\to\java.executable".asFilename());
newConnectedTo:aHostString port:aPortNumber withTimeout:aTimeoutSeconds[edit]
  • This is used to connect to a running Java Bridge on the network. The Java Bridge must be started in server mode on the remote host. After connecting a new connected instance of JAVA::Java is returned.
aHostString - the hostname or IP of the remote machine as String
aPortNumber - the port on which the remote machine is listening as Number
aTimeoutSeconds - a connect timeout in seconds as Number
   Smalltalk: JAVA::Java newConnectedTo:'myHostName' port:4567 withTimeout:30.
   JavaScript: JAVA::Java.newConnectedTo_port_withTimeout("myHostName",4567,30);
newWaitingForConnectOnHost:aListeningAddressString port:aListeningPortNumber withTimeout:aTimeoutSeconds[edit]
  • This is used to wait for incoming connections of a running Java Bridge on the network. The Java Bridge must be started in client mode on the remote host. After connecting a new connected instance of JAVA::Java is returned.
deprecated: aListeningAddressString - no longer used. Can be nil.
aListeningPortNumber - the port on which to listen for incoming connections as Number
aTimeoutSeconds - a connect timeout in seconds as Number, If nil it will wait endless.
  • This will call newWithServer for the first time and then always returns the same connected JAVA::Java instance until the connection was closed, then a new connected instance is returned.
  • If there already is a defaultInstance (see above) - return it. Otherwise return nil. This does not create new connection.
  • This will close all instances of JAVA::Java.

instance protocol[edit]

  • Adds a jar to the running Java VM. If the jar depends on other jars or libraries you have to add them too.
aPath - the path to the jar file as String.
  • Adds a jar to the running Java VM. If the jar depends on other jars or libraries you have to add them too.
aByteArrays - a ByteArray containing the JAR file.
  • Adds a jar to the running Java VM and caches it for subsequent usages. If the jar depends on other jars you have to add them too.
aPath - the path to the jar file as String.
  • Any boxed values in aBlock returned from the JVM are preserved as such. By default autoboxed values are automatically unboxed. This way, the identity of such objects is preserved.
  • Tests if a connection is still established.
return: - true if the connection is still established, else false.
  • Tests if a connection is still responding.
return: - true if the connection is still alive, else false. Does a message round trip.
  • This will close the bridge connection. Depending on in which mode the Java Bridge was started, the Java VM is also closed (-keepAlive startparameter not set).

See Also[edit]

The DOTNET Interface Plugin & Library, which implements a likewise interface for .NET applications/libraries.
Version 1 of the Java Interface Library

Back to Plugins

Copyright © 2014-2020 eXept Software AG