【发布时间】:2014-12-13 01:00:08
【问题描述】:
在我的 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 意思一样吗?这是在哪里记录的?
【问题讨论】:
-
您尝试将元数据放在哪里?顺便说一句,你最后一个问题的答案很简单:clojure.org/metadata
-
好的---如果您尝试过的唯一方法是您当前问题的状态,请尝试以下操作:
:methods [^:static [staticMethod [String String] String] ] -
尝试按照我在上面的评论中指定的注释:不是符号,而是向量。
-
其实开头那句是“符号和集合支持元数据”。
-
不,这意味着符号和集合都可以保存元数据。您只需要注意使用元数据注释的内容。当您说
(meta m)时,您查询的是m引用的对象的元数据,而不是符号m。这是因为只有m评估为集合,而不是符号。
标签: java clojure static static-methods gen-class