【问题标题】:compile Clojure *.clj into *.class, some functions are not generated将 Clojure *.clj 编译成 *.class,有些函数没有生成
【发布时间】:2013-02-17 19:05:20
【问题描述】:

我正在遵循here 的说明,并尝试通过调用 lein jarclj 源生成 Java 类。

但是,当我稍微编辑代码以添加我自己的测试功能时:

(ns some.Example
  (:gen-class))

(defn -main
  [greetee]
  (println (str "Hello " greetee "!")))

(defn -foo []
  "foo bar")

.. 然后继续用 lein jar 生成一个 Java 类文件(我在帖子末尾附加了 project.clj)我发现生成的 jar 包含作为内部类的方法:

$ jar tvf example-1.0.0.jar 
    76 Sun Feb 17 20:56:24 EET 2013 META-INF/MANIFEST.MF
  1225 Sun Feb 17 20:56:24 EET 2013 META-INF/maven/some/example/pom.xml
    87 Sun Feb 17 20:56:24 EET 2013 META-INF/maven/some/example/pom.properties
  2697 Sun Feb 17 20:56:24 EET 2013 some/Example__init.class
  1499 Sun Feb 17 20:56:24 EET 2013 some/Example$loading__4784__auto__.class
  1035 Sun Feb 17 20:56:24 EET 2013 some/Example$_main.class
   565 Sun Feb 17 20:56:24 EET 2013 some/Example$_foo.class
  1771 Sun Feb 17 20:56:24 EET 2013 some/Example.class
   162 Sun Feb 17 18:03:12 EET 2013 project.clj
   129 Sun Feb 17 19:23:54 EET 2013 some/Example.clj

并且 some.Example 类仅包含 ma​​in 方法,但不包含 foo

$ javap some.Example
public class some.Example {
  public static {};
  public some.Example();
  public java.lang.Object clone();
  public int hashCode();
  public java.lang.String toString();
  public boolean equals(java.lang.Object);
  public static void main(java.lang.String[]);
}

所以问题是:我们如何指定一个 clj Clojure 文件,该文件生成一个带有许多静态和实例方法的 Java 类,目的是从 Java 代码中调用这些方法?

project.clj 用于 *lein jar* 操作

(defproject some/example "1.0.0"
  :description "A sample project"
  :dependencies [[org.clojure/clojure "1.4.0"]]
  :aot [some.Example]
  :source-paths ["."]
  )

【问题讨论】:

    标签: clojure leiningen


    【解决方案1】:

    您需要声明您的类将拥有的方法:

    (ns some.Example
      (:gen-class
         :methods [[foo [] String]]))
    

    请注意,这将 foo 声明为非静态方法,因此它还需要采用 this 参数:

    (defn -foo [this]
      "foo bar")
    

    如果你希望方法是静态的,你需要附加一些元数据:

    (ns some.Example
          (:gen-class
             :methods [#^{:static true}[bar [] int]]))
    (defn -bar []
      3)
    

    尝试阅读this,它会更快一些。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-12
      • 1970-01-01
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多