5

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?

1 Answer 1

7

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.