如何在Clojure中使用genclass扩展Java类时调用超类? [英] How to call super class when extending a Java class using genclass in Clojure?

查看:205
本文介绍了如何在Clojure中使用genclass扩展Java类时调用超类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从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-classed 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆