Using Java from APLX
You can use APLX to interface to classes written in the Java language. This can be very useful if there's a pre-existing Java library that solves a problem which would otherwise require you to write some new APL code. The following examples work in all versions of APLX V4 or later - Windows, Macintosh and Linux.
To create an object from an existing Java class you use the ⎕NEW system function, specifying 'java' as the left argument. For example:
⍝ Construct a 'Date' object
myDate←'java' ⎕NEW 'java.util.Date'
⍝ Demonstrate some method calls
myDate.toString
Mon Feb 02 13:32:47 GMT 2009
myDate.getYear
109The first time that you create a Java object, APLX loads a copy of the Java Virtual Machine (JVM). Calls from APLX to Java objects are then passed to the JVM for evaluation and the results returned to APLX.
Because APLX is an array language, we can also do things like this:
⍝ Make 12 identical copies of myDate
dateList←myDate.⎕CLONE 12
⍝ Change the month in each copy to a different value
dateList.setMonth((⍳12)-⎕IO)
⍝ Show the result
(12 1⍴dateList).toString
Fri Jan 02 13:43:20 GMT 2009
Mon Feb 02 13:43:20 GMT 2009
Mon Mar 02 13:43:20 GMT 2009
Thu Apr 02 13:43:20 BST 2009
Sat May 02 13:43:20 BST 2009
Tue Jun 02 13:43:20 BST 2009
Thu Jul 02 13:43:20 BST 2009
Sun Aug 02 13:43:20 BST 2009
Wed Sep 02 13:43:20 BST 2009
Fri Oct 02 13:43:20 BST 2009
Mon Nov 02 13:43:20 GMT 2009
Wed Dec 02 13:43:20 GMT 2009Here's a slightly more useful example in which we use Java to create a ZIP file:
⍝ Create a new ZIP file called 'newfile.zip'
outStream←'java' ⎕NEW 'java.io.FileOutputStream' 'C:\simon\newfile.zip'
zip←'java' ⎕NEW 'java.util.zip.ZipOutputStream' outStream
⍝ We'll add a single file within the ZIP file. For this demo, let's
⍝ create a dummy file 'MyFile.txt'. In practice we'd add some real files,
⍝ reading them either by using APL's built-in file functions like
⍝ ⎕NTIE and ⎕NREAD, or by using Java.
zip.putNextEntry ('java' ⎕NEW 'java.util.zip.ZipEntry' 'MyFile.txt')
zip.write ¨⎕af ¯1 ⎕tr 'Hello world, this is some text'
⍝ Say that file has been added. We could loop here to add some more
zip.closeEntry
⍝ All done
zip.closeFor an example of code which uses Java to send an e-mail to a SMTP server requiring authentication, see here
