繁体   English   中英

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

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

我想在类的方法中使用通过gen-class构造的类的实例。

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

(ns example
  (:gen-class))

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM