user235273
user235273

Reputation:

How to call super class when extending a Java class using genclass in Clojure?

I want to call a method in the super class from Clojure. I am extending a Java class using :gen-class.

(ns subclass.core
    (:gen-class
     :extends Baseclass))

(defn greet [] 
    "Hello from core")  ; how to call super.greet()?

(defn -main [& args]
    (greet))

Java Baseclass

public class Baseclass {
    public String greet() {
        return "Hello from Baseclass";
    }
}

Edit: as the linked example I tried

 (ns subclass.core
    (:gen-class
     :extends Baseclass
     :exposes-methods {greet pgreet})
    (:import Baseclass))

(defn greet []
    (.pgreet (Baseclass.)))

(defn -main [& args])

But when I call (greet) I am getting the error

IllegalArgumentException No matching field found: pgreet for class Baseclass  clojure.lang.Reflector.getInstanceField (Reflector.java:271)

Is this the right way to call the super class method?

Update: Got it. We create a different method which will intern call the base class method. https://en.wikibooks.org/wiki/Clojure_Programming/Examples/API_Examples/Java_Interaction#genclass
NB: that's not what the linked answer says.

Upvotes: 3

Views: 1181

Answers (1)

Nathan Davis
Nathan Davis

Reputation: 5766

This question has already been asked and answered.

Your example fails because your greet function tries to call the pgreet method on an instance of BaseClass. You need to create an instance of the gen-classed class.

For example, something like this:

(ns subclass.core
  (:gen-class
   :extends Baseclass
   :exposes-methods {greet pgreet})
  (:import Baseclass))

;; You need to define a function for the overridden method
(defn greet- [this]
  (. this (pgreet)))

(defn greet []
  ;; You need to use the *gen-class*ed class, not BaseClass
  (. (new subclass.core) (greet))))

Upvotes: 1

Related Questions