2012-11-12 32 views
2

我想通過proxy生成一個類(不是對象),並且該類將在稍後實例化。如何從代理中獲取「類」?

我發現Clojure的代理方法的例子似乎主要是最常見的Java內部類的情況,即當我們只定義一個類,因爲我們要創建它的一個實例處理。

在我的情況下,我想定義一個真正的類 - 可以稍後加載的類。但是我想定義它,而不必使用gen-class的複雜性編譯它。

請問可不可以呢?或者是gen-class的要求?

回答

1

如果定義Clojure Protocol,然後創建一個實現該協議,那麼你就可以創建實例以後是簡單的類的類。

(defprotocol myProtocol 
    (doStuff [this x y]) 
    (getA [this]) 
    (setA [this n])) 

(deftype Foo [ ^:unsynchronized-mutable a] 
    myProtocol 
    (doStuff [this x y] (+ x y a)) 
    (getA [this] a) 
    (setA [this n] (set! a n))) 

(def a (Foo. 42)) 

user> (.getA a) 
42 
user> (.setA a 41) 
41 
user> (.getA a) 
41 
user> (.doStuff a 3 4) 
48 
user> (class a) 
user.Foo 

時生成的類進入一個包具有相同名稱作爲所謂deftype

命名空間