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?
The generated class automatically defines all of the non-private methods of its superclasses/interfaces. This parameter can be used to specify the signatures of additional methods of the generated class.
In Clojure we can do that using the special form new or using a dot ( . ) notation. The new special form has the class name of the Java class we want to create an instance of as argument followed by arguments for the Java class constructor. With the dot notation we place a .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With