javasmalltalksmalltalkx

How to access and use Java library/package in Smalltalk


It was mentioned in comments on another Stackoverflow question that it may be possible to access Java packages from Smalltalk.

However, I have not been able to find any information regarding this on searching the net.

Any insight in this regard will be highly appreciated.


Solution

  • Essentially there three ways to (re)use Java code in Smalltalk/X:

    Each of these options have their own pros and cons, as usual. I'm going to focus on the last one - stx:libjava - this is the one @tukan had in mind.

    stx:libjava

    Disclaimer: I (re)designed and (re)implemented most of stx:libjava so take my views with grain of salt as I'm biased.

    stx:libjava is a package that allows loading Java code into Smalltalk/X environment and execute it. Once loaded, there's no difference between Java code and Java objects and Smalltalk code and Smalltalk objects - they both live in the same runtime (virtual machine if you prefer). In fact, most of the runtime does not know (and does not care) whether given object or method is actually a Smalltalk or Java one. There are only two components inside the runtime that distinguish - that's a bytecode interpreter (since Smalltalk/X bytecode is very different from Java bytecode) and JIT-compiler frontend (for the very same reason). Because of that there's no difference performance-wise between executing Smalltalk or Java code.

    Simple Example

    Here's an example of using SAXON XSLT processor implemented in Java from Smalltalk/X:

    [
        config := JAVA net sf saxon Configuration new.
        config setAllNodesUntyped: true.
        factory := JAVA net sf saxon TransformerFactoryImpl new: config.
        stylesheet := factory newTemplates:
            (JAVA javax xml transform stream StreamSource new:
                (JAVA java io File new: 'cd.xsl')).
        input :=
            (JAVA javax xml transform stream StreamSource new:
                (JAVA java io File new: 'cd.xml')).
        output :=
            (JAVA javax xml transform stream StreamResult new:
                (JAVA java io File new: 'cd.html')).
        transformer := stylesheet newTransformer.
        transformer transform: input to: output.
    ] on: JAVA java io IOException do:[:ex|
        Transcript showCR:'I/O error: ', ex getMessage.
        ex printStackTrace.
    ] on: JAVA javax xml transform TransformerException  do:[:ex|
        Transcript showCR:'Transform error: ', ex getMessage.
        ex printStackTrace.
    ].
    

    Further references

    Following resources may give you better idea what is it about: