2016-08-18 40 views
1

我特别试图测试Cjoures声称它可以“无缝地”与Java一起工作。一般来说,如何翻译Java代码:将Java对象和方法调用转换为Clojure代码

object1.object2(some_args).object3.object4(some_other_args).object5.objectnth.method(arg‌​1, arg2, argn); 

to Clojure?链中的一些对象可能是静态类,静态方法或类变量,其中一些是接口。这似乎并不简单。例如,图形库中的对象。我记得有一次我试图创建一个对象(Graphics),Clojure说它不知道那个类的Graphics。

非常感谢!

lisprog

+2

你有具体的例子吗?上面的示例有点含糊。举个例子,你可以先看http://clojuredocs.org/clojure.core/doto。另请参阅http://clojure-doc.org/articles/language/interop.html –

+0

“链中的一些对象可能是静态类”[编号](http://stackoverflow.com/q/1215881/ 5044950) –

+0

@AlanThompson实际上,['..'](https://clojuredocs.org/clojure.core/_ ..)在这种情况下更合适。 –

回答

1

让我们的Java示例:

public class Test { 

    public Test a; 

    public Test getA() { 
     return this.a; 
    } 

    public Test add(Test a) { 
     this.a = a; 
     return this; 
    } 

    public int foo(int a, int b, int c) { 
     return a+b+c; 
    } 

    public long foovar(Long... ai) { 
     long r = 0; 
     for (long i:ai) r+= i; 
     return r; 
    } 
} 

,并显示出一堆的方式访问内部对象:

(import 'Test) 

;; create all the objects 
(def t1 (Test.)) 
(def t2 (Test.)) 
(def t3 (Test.)) 
(def t4 (Test.)) 
(def t5 (Test.)) 
(def t6 (Test.)) 

;; and lets chain them together: 
(.add t1 (.add t2 (.add t3 (.add t4 (.add t5 t6))))) 

;; verify using member access: 
(= t6 (.. t1 a a a a a)) ;; true 

;; verify using method call: 
(= t6 (.. t1 getA getA getA getA getA)) ;; true 

;; and mixed access 
(= t6 (.. t1 a a getA a a)) ;; true 

;; lets invoke foo: 
(.. t1 getA getA getA getA getA (foo 1 2 3)) ;; 6 

;; and invoke foovar: 
(.. t1 getA getA getA getA getA (foovar (into-array[1 2 3]))) ;; 6 

现在,我们还可以创建辅助功能:

;; get the object at depth n using functions 
(defn get-nth-function [o n] 
    (first (drop n (iterate (memfn getA) o)))) 

;; get the object at depth n using member access. 
;; This same notation could also be used for function, 
;; however I just wanted to show an example of memfn 
(defn get-nth-member [o n] 
    (first (drop n (iterate #(.a %) o)))) 

;; lets verify: 
(= t6 (get-nth-member t1 5)) ;; true 

;; lets invoke foovar on object position 6, 
;; on a range of numbers from 1 to 10 
(.foovar (get-nth t1 5) (into-array (range 10))) ;; 45 

这应该显示clojure和java之间交互的灵活性。当你有静态成员时,你可以像System/out那样通过/来访问它们(尽管.也可以)。请务必完整阅读http://clojure-doc.org/articles/language/interop.html,如果您还没有收到任何东西,请告诉我们。

+1

非常感谢你!相信我;我已经多次从clojure官方网站上阅读过java-clojure interop。我很高兴能从你这样的人那里得到一些慷慨解答知识的答案,而不仅仅是告诉我RTFM。再次感谢 ! – lisprogtor