[英]How do I get the instance of the class when using gen-class
I want to use the instance of the class constructed via gen-class in a method of the class. 我想在类的方法中使用通过gen-class构造的类的实例。
How do I access it? 我该如何访问它? What do I have insert for "this" in the following example: 在以下示例中,我为“this”插入了什么:
(ns example
(:gen-class))
(defn -exampleMethod []
(println (str this)))
Or is it impossible when using gen-class? 或者在使用gen-class时是不可能的?
The first argument of Clojure functions corresponding to a method generated by gen-class takes the current object whose method is being called. 与gen-class生成的方法对应的Clojure函数的第一个参数采用其方法被调用的当前对象。
(defn -exampleMethod [this]
(println (str this)))
In addition to this, you have to add a :methods
option to gen-class
when you define a method which comes from neither a superclass nor interfaces of the generated class. 除此之外,当您定义既不是超类也不是生成的类的接口的方法时,您必须向gen-class
添加:methods
选项。 So a complete example would be as follows. 所以一个完整的例子如下。
(ns example)
(gen-class
:name com.example.Example
:methods [[exampleMethod [] void]])
(defn- -exampleMethod
[this]
(println (str this)))
user> (compile 'example)
example
user> (.exampleMethod (com.example.Example.))
com.example.Example@73715410
nil
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.