Clojure 5 - Calling Java

Download Report

Transcript Clojure 5 - Calling Java

Clojure 5
Clojure and Java
The JVM


Clojure runs on the JVM (Java Virtual Machine)
Clojure can use Java objects, methods, and fields



This includes Java’s collections data types,
In general, Clojure’s datatypes are preferable because they are
immutable and persistent
Possibly the best use of Java in Clojure is to make Swing
GUIs
2
Imports

(import import-lists*)



Only classes can be imported, not entire packages


Imports the named Java classes
Example:
(import '(java.awt.Color) '(java.awt.Point))
There is no equivalent of import java.util.*;
All of java.lang is implicitly imported, along with
everything in clojure.core
3
Creating Java objects


(new JavaClassName args*)

Creates and returns a new Java object of the specified class

Syntactic sugar: (JavaClassName. args*)

Notice the period, it’s important!
Examples:

(def rnd (new java.util.Random))

(def c (java.awt.Color. 255 128 0))
4
Calling an object’s instance methods

(. JavaObject methodName args*)

(.methodName JavaObject args*)


Calls the Java object’s method with the supplied
arguments
Examples:


(. rnd nextInt 10)
(.nextInt rnd 10)
5
Accessing instance variables

(. JavaObject fieldName)

Returns the value in the named field of the Java object
Example:


After (def p (new java.awt.Point 20 40)),
(. p x) will return 20.
6
Calling static methods

(JavaClass/staticMethodName args*)

Calls the static method of the class
Example: (System/currentTimeMillis)

7
Accessing static variables

(JavaClass/staticMethodName args*)

Returns the value in the static field of the class
Example: (java.awt.Color/CYAN)

8
Making multiple calls to an object

doto(JavaInstanceOrClass methodCalls*)

Uses the Java object or class as the receiver for any
number of method calls
Example:


(doto
new java.util.HashMap
(.put "a" 1)
(.put "b" 2) )
9
Proxy

(proxy [Class? Interfaces*] [constructorArgs*]
functions*)

Creates a Clojure class to do the work that would be done by a
Java class in Java
The optional Class? parameter names the superclass (and if
omitted, defaults to Object)
If the class’s constructor requires parameters, those are provided
in the second vector, otherwise the second vector is empty, []
The functions are usual Clojure functions (omitting the defn),
and have the form (name [params*] body) or (name
([params*] body) ([params+] body) ...)



10
Example proxy

(. convert-button
(addActionListener
(proxy [ActionListener] []
(actionPerformed [evt]
(let [c (Double/parseDouble
(. temp-text (getText)))]
(. fahrenheit-label
(setText (str (+ 32 (* 1.8 c))
" Fahrenheit"))))))))
11
In addition…


There are also functions for dealing with Java arrays,
and for treating Java methods as first-class objects
These are not covered here
12
The End
13