如何使用clojure的Gen-class生成生成静态方法?

时间:2014-10-17 12:31:36

标签: java clojure static static-methods gen-class

在我的Clojure代码中,我想生成一个包含静态方法(名为staticMethod)的类文件,该方法稍后在Java程序的静态上下文中调用。

我试过(Clojure):

(ns com.stackoverflow.clojure.testGenClass
  (:gen-class
     :name com.stackoverflow.clojure.TestGenClass
     :prefix "java-"
     :methods [
               [#^{:static true} staticMethod [String String] String]
              ]))

(def ^:private pre "START: ")

(defn #^{:static true} java-staticMethod [this text post]
  (str pre text post))

和(Java):

package com.stackoverflow.clojure;

public class TestGenClassTest {

    private TestGenClassTest() {
    }

    public static void main(String[] args) {
        TestGenClass.staticMethod("Static call from Java!", " :END");
    }
}

https://kotka.de/blog/2010/02/gen-class_how_it_works_and_how_to_use_it.html上我读到了:

  

通过将#^ {:static true}元数据添加到方法声明中   你也可以定义静态方法。

无论我在哪里放置#^{:static true} Java编译器总是说:

  

无法对非静态方法进行静态引用   testGenClass类型的staticMethod(String,String)

如何在Clojure中定义静态方法? #^{:static true}^:static意味着相同吗?这记录在哪里?

1 个答案:

答案 0 :(得分:9)

当kotka说要注释方法声明时,他“obviosly”意味着整个 vector 持有声明:

:methods [^:static [staticMethod [String String] String] ]

遗憾的是,这种简洁的措辞是Clojure文档的典型代表。