10 Java Interop
10.2 Lisp Flavored Erjang
10.2.3 Getting Started
As you might expect, we use lfetool
to work with Erjang :-) Here's how you
install it:
$ lfetool install erjang
On a fast internet connection, this should take less than 3 minutes to download
Erjang, download Erlang/OTP, and then create the necessary .jar
files.
Once lfetool
has downloaded, compiled, and installed Erjang, you'll be
ready for the next step: hopping into the REPL:
$ lfetool repl jlfe
LFE Shell V5.10.4 (abort with ^G)
> (* 2 (+ 1 2 3 4 5 6))
42
> (* 2 (lists:foldl (lambda (n acc) (+ n acc)) 0 (lists:seq 1 6)))
42
For that to work, you will either need to have lfe
in your path, or be in
an LFE project directory that you created with lfetool
.
10.2.4 Using LFE Projects from Erjang
If you've got an LFE project you have already created and want to see how it
runs on Erjang with jlfe
, go ahead and start up the jlfe
REPL in that
project directory -- cd
to your project dir and start the REPL like we did
in the above example.
For those that don't have one, try this out:
$ git clone https://github.com/lfe/exemplar.git
$ cd exemplar
$ lfetool repl jlfe
LFE Shell V5.10.4 (abort with ^G)
Now start up the REPL and call some functions:
> (slurp '"src/exemplar-html.lfe")
#(ok exemplar-html)
> (p '"My paragraph.")
"<p>My paragraph.</p>"
> (html (body (div (p '"A paragraph in my page."))))
"<html><body><div><p>A paragraph in my page.</p></div></body></html>"
>
10.2.5 Calling Java from LFE
10.2.5.1 Static Method on a Class
Here's an example of calling as static method on a Java class from LFE:
> (java.lang.Math:sin 0.5)
0.479425538604203
>
10.2.5.2 Static Field on a Class
For right now, in order to activate the Erjang BIFs java:get_static/2
and
java:call/4
, you need to create a java
module:
cat > java.lfe
(defmodule java)
(defun noop ()
'noop)
^D
Start up the REPL:
$ lfetool repl jlfe
Once your java
module is compiled, you'll be able to access static fields:
> (c 'java)
#(module java)
> (java:get_static 'java.lang.Math 'PI)
3.141592653589793
10.2.5.3 Member on an Instance
In order to call members on instances, you need to create an instance first:
> (set rand-obj (java.util.Random:new))
#B()
You can confirm the type that you just created:
> (java:call rand-obj 'getClass '() '())
java.util.Random
Erjang's java:call/4
function takes two additional parameters that we're
not using right now: types and arguments.
Here's how you call the various Random
instance methods:
> (call rand-obj 'nextInt)
1845347843
> (call rand-obj 'nextDouble)
0.34850947916661346
You may also make the Erjang call:
> (java:call rand-obj 'nextInt '() '())
-2083227816
> (java:call rand-obj 'nextDouble '() '())
0.8218552203785259
10.2.5.4 Working with Files from Java
TBD