Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the instance of the class when using gen-class

Tags:

clojure

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?

like image 251
DerRoteBaron Avatar asked Apr 29 '15 10:04

DerRoteBaron


People also ask

What does Gen class do in Clojure?

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.

How do you create a class in Clojure?

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 .


1 Answers

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
like image 96
tnoda Avatar answered Nov 15 '22 07:11

tnoda