在“我的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的意思相同吗?这在哪里记录?

最佳答案

当kotka说要注释方法声明时,他“很明显”是指整个带有声明的向量:

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

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

08-06 02:34