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

时间:2015-04-29 10:49:12

标签: clojure

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

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

// event management
$("input.box[type=checkbox]").change(function() {
    var name = $(this).attr("name");
    $("input:checkbox[name='$name']").attr("checked", true);
    $.cookie(name, $(this).prop('checked'), {
        path: '/',
        expires: 365
    });
});

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

1 个答案:

答案 0 :(得分:7)

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

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

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

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
相关问题