2015-11-03 79 views
1

我曾嘗試使用gen-and-load-classclojure.core,然後使用自定義類加載器調用defineClass與生成的字節碼,但是當我打電話我如何用Clojure在運行時定義一個Java類,並創建實例

(foo.bar.MyClass.) 

我「M越來越

CompilerExceptionjava.lang.NoClassDefFoundError: Could not initialize class foo.bar.MyClass 

UPDATE:

所以我用DEFTYPE通過@Elogent的建議:

(defprotocol Struct 
    (getX [this path] "Get value") 
    (setX [this ^long value path] "Get value")) 
(deftype Foo 
    [ 
    ^{:tag long :unsynchronized-mutable true} a 
    ^{:tag long :unsynchronized-mutable true} b 
    ^{:tag long :unsynchronized-mutable true} c] 
    Struct 
    (getX 
    [this [head & tail]] 
    (let [field (condp = head 
      'a a 
      'b b 
      'c c)] 
     (if (empty? tail) 
     field 
     (getX field tail)))) 
    (setX 
    [this value [head & tail]] 

    (if (empty? tail) 
     (condp = head 
      (set! a (long value)) 
      (set! b (long value)) 
      (set! c (long value))) 
     (condp = head 
      (setX a value tail) 
      (setX b value tail) 
      (setX c value tail))))) 

AOT後,當我做javap Foo.class我:

public final class struct.core.Foo implements struct.core.Struct,clojure.lang.IType { 
    public static final clojure.lang.Var const__0; 
    public static final java.lang.Object const__1; 
    public static final clojure.lang.Var const__2; 
    public static final java.lang.Object const__3; 
    public static final clojure.lang.Var const__4; 
    public static final clojure.lang.AFn const__5; 
    public static final clojure.lang.AFn const__6; 
    public static final clojure.lang.AFn const__7; 
    public static final clojure.lang.Var const__8; 
    public static final clojure.lang.Var const__9; 
    public static final clojure.lang.Var const__10; 
    public static final clojure.lang.Var const__11; 
    public static final clojure.lang.Var const__12; 
    long a; 
    long b; 
    long c; 
    public static {}; 
    public struct.core.Foo(long, long, long); 
    public static clojure.lang.IPersistentVector getBasis(); 
    public java.lang.Object setX(java.lang.Object, java.lang.Object); 
    public java.lang.Object getX(java.lang.Object); 
} 

這正是我需要的。謝謝@Elogent!

+1

你試圖解決什麼問題?換句話說,你需要這個你定義的Java類的目的是什麼? –

+0

我正在構建原型,允許構建簡潔的功能和緩存不經意的數據結構。爲此,我需要構建等效的C strict,模型數據結構作爲數組,而不使用引用等。 – Lambder

+0

爲什麼?在這種情況下['defrecord'](http://clojuredocs.org/clojure.core/defrecord)或['deftype'](http://clojuredocs.org/clojure.core/deftype)有什麼問題? –

回答

1

除非您絕對需要Java類的所有靈活性,否則我會建議您使用deftype來代替。正如here,deftype所解釋的,您可以通過慣用的方式訪問較低級別的構造,如基元類型和可變性。

相關問題