跳转到内容

Clojure 编程/示例/API 示例/Java 交互

来自 Wikibooks,开放世界中的开放书籍
(map (memfn charAt i) ["fred" "ethel" "lucy"] [1 2 3])
-> (\r \h \y)
(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

[编辑 | 编辑源代码]
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

[编辑 | 编辑源代码]
user=> (into-array (map double-array [[1.0] [2.0]])) 
#<double[][] [[D@1fa1bb6> 
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.) )
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}
华夏公益教科书