Reputation: 353
I want to use the instance of the class constructed via gen-class in a method of the class.
How do I access it? What do I have insert for "this" in the following example:
(ns example
(:gen-class))
(defn -exampleMethod []
(println (str this)))
Or is it impossible when using gen-class?
Upvotes: 5
Views: 114
Reputation: 1524
The first argument of Clojure functions corresponding to a method generated by gen-class takes the current object whose method is being called.
(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. 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
Upvotes: 7