How to get class instance when using gen-class

I want to use an instance of a class built with a gen class in a class method.

How do I access it? What should I insert for "this" in the following example:

(ns example (:gen-class)) (defn -exampleMethod [] (println (str this))) 

Or is this not possible when using the gen class?

+5
source share
1 answer

The first argument of the Clojure functions, corresponding to the method generated by the gen class, takes the current object whose method is called.

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

In addition to this, you must add the :methods parameter to the gen-class when you define a method that comes from neither the superclass nor the interfaces of the generated class. Thus, a complete example will be as follows.

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 
+7
source

All Articles