tat*_*tsy 3 clojure clojure-java-interop
我现在正在用 Clojure 创建一个类对象,它有一个返回对象本身的方法。
用 Java 编写,我想制作的对象是,
class Point {
public double x;
public double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point copy() {
return new Point(this.x, this.y);
}
}
Run Code Online (Sandbox Code Playgroud)
我写的当前 clojure 代码就像,
(ns myclass.Point
:gen-class
:prefix "point-"
:init init
:state state
:constructors {[double double] []}
:methods [[copy [] myclass.Point]]))
(defn point-init [x y]
[[] {:x x :y y}])
(defn point-copy [this]
this)
Run Code Online (Sandbox Code Playgroud)
但是,我收到如下错误。
java.lang.ClassNotFoundException: myclass.Point
Run Code Online (Sandbox Code Playgroud)
虽然我用谷歌搜索过这个问题,但我找不到任何答案。有谁知道这个问题的解决方案?
预先感谢您的帮助。
我不确定这是唯一的方法,但是,为了在方法签名中使用生成的类类型,您可以分两步生成类 - 尽管它仍然在一个文件中并一次性编译:
gen-class仅使用构造函数调用gen-class再次调用状态,完整的构造函数和方法。我尝试了包括前向声明在内的各种方法,但最终只有上述方法有效。我确实扩展了你的例子。请注意,该copy方法不是非常有用,因为它Point是不可变的,但您可能希望为您的类提供修改器。
完整列表:
(ns points.Point)
;; generate a simple class with the constructors used in the copy method
(gen-class
:name points.Point
:init init
:constructors {[] []
[double double] []})
;; generate the full class
(gen-class
:name points.Point
:prefix pt-
:main true
:state coordinates
:init init
:constructors {[] []
[double double] []}
:methods [[distance [points.Point] double]
[copy [] points.Point]])
(defn pt-init
([] (pt-init 0 0))
([x y]
[[] {:x x :y y}]))
(defn pt-copy
"Return a copy of this point"
[this]
(points.Point. (:x (.coordinates this)) (:y (.coordinates this))))
(defn pt-distance [^points.Point this ^points.Point p]
(let [dx (- (:x (.coordinates this)) (:x (.coordinates p)))
dy (- (:y (.coordinates this)) (:y (.coordinates p)))]
(Math/sqrt (+ (* dx dx) (* dy dy)))))
(defn pt-toString [this]
(str "Point: " (.coordinates this)))
;; Testing Java constructors and method call on Point class
(import (points Point))
(defn pt-main []
(let [o (Point.)
p (points.Point. 3 4)]
(println (.toString o))
(println (.toString p))
(println (.distance o p))
(println (.distance p (.copy p)))))
Run Code Online (Sandbox Code Playgroud)
为了生成类,请project.clj使用以下行进行配置
:aot [points.Point]
Run Code Online (Sandbox Code Playgroud)
测试lein给出:
tgo$ lein clean
tgo$ lein compile
Compiling points.Point
tgo$ lein run
Point: {:x 0, :y 0}
Point: {:x 3.0, :y 4.0}
5.0
0.0
Run Code Online (Sandbox Code Playgroud)