如何在Clojure中使用genclass扩展Java类时调用超类? [英] How to call super class when extending a Java class using genclass in Clojure?
问题描述
我想从Clojure中调用超类中的方法。我正在使用扩展Java类:gen-class
。
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
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?
更新:明白了。我们创建了一个不同的方法,它将实习调用基类方法。
https://en.wikibooks.org/wiki/ Clojure_Programming / Examples / API_Examples / Java_Interaction #genclass
注意:这不是链接的答案所说的。
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.
推荐答案
您的示例失败因为 greet
函数尝试在 BaseClass $的实例上调用
pgreet
方法C $ C>。您需要创建 gen-class
ed类的实例。
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-class
ed class.
例如,类似这样的事情: / p>
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))))
这篇关于如何在Clojure中使用genclass扩展Java类时调用超类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!