使用 gen-class 时如何获取 class 的实例

How do I get the instance of the class when using gen-class

我想在 class.

的方法中使用通过 gen-class 构造的 class 的实例

如何访问它?在以下示例中,我为 "this" 插入了什么:

(ns example
  (:gen-class))

(defn -exampleMethod []
  (println (str this)))

或者使用gen-class是不可能的?

对应于 gen-class 生成的方法的 Clojure 函数的第一个参数采用正在调用其方法的当前对象。

(defn -exampleMethod [this]
  (println (str this)))

除此之外,当您定义既不是来自 superclass 也不是生成的 [= 接口的方法时,您必须向 gen-class 添加 :methods 选项24=]。所以一个完整的例子如下。

example.clj

(ns example)

(gen-class
 :name com.example.Example
 :methods [[exampleMethod [] void]])

(defn- -exampleMethod
  [this]
  (println (str this)))

REPL

user> (compile 'example)
example

user> (.exampleMethod (com.example.Example.))
com.example.Example@73715410
nil