Clojure Programming/Examples/API Examples/Java Interaction

From Wikibooks, open books for an open world
Jump to: navigation, search

memfn[edit]

(map (memfn charAt i) ["fred" "ethel" "lucy"] [1 2 3])
-> (\r \h \y)

proxy[edit]

(defn rev-vector-seq
  [v]
  (when (< 0 (count v))
    (proxy [clojure.lang.ISeq] []
      (seq   [] this)
      (first [] (peek v))
      (rest  [] (rev-vector-seq (pop v)))))) 
(doto (javax.swing.JFrame.)
  (.addKeyListener (proxy [java.awt.event.KeyListener] []
       (keyPressed [e] (println (.getKeyChar e) " key pressed"))
       (keyReleased [e] (println (.getKeyChar e) " key released"))
       (keyTyped [e] (println (.getKeyChar e) " key typed"))))
  (.setVisible true))

into-array[edit]

user=> (into-array [1 2 3])
#<Integer[] [Ljava.lang.Integer;@15fadcf>
user=> (into-array [1 2 "asd"])
java.lang.IllegalArgumentException: array element type mismatch (NO_SOURCE_FILE:0)
user=>

double-array[edit]

user=> (into-array (map double-array [[1.0] [2.0]])) 
#<double[][] [[D@1fa1bb6> 

genclass[edit]

expmeth/ClassA.java: 
package expmeth; 
public class ClassA { 
    public void hello() { 
        System.err.println("hello from Java!"); 
    } 
    public void hello(int x) { 
        System.err.println("hello from Java " + x); 
    } 
} 

expmeth/TestMe.clj: 
(ns expmeth.TestMe 
  (:gen-class 
   :extends expmeth.ClassA 
   :exposes-methods {hello helloSuper})) 
(defn -helloSuper 
  ([this] 
     (.hello this) 
     (println "hello from clojure!")) 
  ([this x] 
     (.hello this x) 
     (println "hello from clojure..." x))) 
testing: 
(.helloSuper (expmeth.TestMe.) 17) 
(.helloSuper (expmeth.TestMe.) )

supers[edit]

user=> (import [javax.swing JFrame])
javax.swing.JFrame
user=> (supers JFrame)
#{java.awt.Component java.awt.Frame java.awt.Container 
java.awt.Window java.awt.MenuContainer javax.swing.RootPaneContainer 
java.lang.Object java.awt.image.ImageObserver java.io.Serializable 
javax.swing.WindowConstants javax.accessibility.Accessible}