简体   繁体   English

如何从Clojure调用Gen类方法

[英]How to call a gen-class method from clojure

I'm Using gen-class to generate Java-classes from my Clojure code. 我正在使用gen-class从我的Clojure代码生成Java类。 In order to make gen-class work, I need to add an additional first parameter to all methods that will be added to the class (here called this ). 为了使gen-class起作用,我需要向将添加到该类的所有方法(此处称为this )中添加一个附加的第一个参数。

(ns com.stackoverflow.clojure.testGenClass
  (:gen-class
     :name com.stackoverflow.clojure.TestGenClass
     :implements [com.stackoverflow.clojure.TestGenClassInterface]
     :prefix "java-"))

(def ^:private pre "START: ")

(defn java-addToString [this text post]
  (str pre text post))

After compilation, calling the method in a Java-context works fine. 编译后,在Java上下文中调用该方法可以正常工作。

(def var (com.stackoverflow.clojure.TestGenClass.))
(.addToString var "Aus Clojure heraus (Methode 1)." " :ENDE")
(. var addToString "Aus Clojure heraus (Methode 2)." " :ENDE")

But how can I start it directly from Clojure? 但是,如何直接从Clojure启动它?

Thge following does not work, since the first parameter is missing. 由于缺少第一个参数,因此无法进行跟随。

(java-addToString "TexT" " :END")

Is it good practice to simply call the function with an empty first parameter? 优良作法是简单地使用空的第一个参数调用该函数吗?

(java-addToString "" "TexT" " :END")

Or should I add a function (eg addToString ) that I use internally and call this function from the one that will be added as a method to the class-file? 还是应该添加一个内部使用的函数(例如addToString ),然后从将作为方法添加到类文件的函数中调用此函数?

To want to treat the same code as a method on a generated class and as a function separate from said class seems a bit smelly to me (in the sense of code smell, something that indicates a problem somewhere in the design). 想要将相同的代码当作生成类上的方法以及与所述类分开的函数来对待,这在我看来有点臭(在代码气味的意义上,这表明设计中某处存在问题)。

Perhaps addToString should be a static method? 也许addToString应该是静态方法?

Perhaps you should make an add-to-string function that can be used directly in clojure, and also called by the addToString method? 也许您应该创建一个可以直接在clojure中使用并且还可以通过addToString方法调用的add-to-string函数?

We'd need to know more about your larger design before we know the best answer, but I suspect it is one of those. 在知道最佳答案之前,我们需要了解更多有关您较大的设计的信息,但我怀疑这是其中之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM