如何在Clojure中使用genclass扩展Java类时调用超类?

时间:2016-12-14 15:43:01

标签: java clojure

我想从Clojure中调用超类中的方法。我正在使用:gen-class扩展Java类。

(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";
    }
}

修改:作为我尝试的链接示例

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

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

(defn -main [& args])

但是当我打电话(问候)时,我收到了错误

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

这是调用超类方法的正确方法吗?

更新:明白了。我们创建了一个不同的方法,它将实习调用基类方法。 https://en.wikibooks.org/wiki/Clojure_Programming/Examples/API_Examples/Java_Interaction#genclass
注意:这不是链接的答案所说的。

1 个答案:

答案 0 :(得分:1)

此问题已经askedanswered

您的示例失败,因为您的greet函数尝试在pgreet的实例上调用BaseClass方法。您需要创建gen-class ed类的实例。

例如,像这样:

(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))))