4

我在引用通过:gen-class.

我可以展示的最小示例是:

(defproject test-proj
  :dependencies [[org.clojure/clojure "1.8.0"]] 
  :aot [test-proj.test])

(ns test-proj.test
  (:gen-class))

(defn -main []
  (println test_proj.test)) ; Error here

问题是,这会ClassNotFoundException在标记线上产生一个。

(我尝试了上述文件-和.围绕那个,我需要下划线来引用。)_project.clj-maintest_proj.test

如果我进入项目根文件,没有target文件夹,所以它不会生成类。如果我进入终端并运行lein compile,它会在 下生成所需的类target,并且上面的代码运行没有错误。这是一个糟糕的解决方法。如果我修改文件并忘记手动重新编译它怎么办?在我每次执行clean.

作为在黑暗中的镜头,我尝试在宏compile下方使用:ns

(compile 'test-proj.test)

如果我使用破折号,compile似乎什么都不做。我可能会误解它的用法,但它不会在target. 如果我使用下划线,它会给出一个异常,指出找不到命名空间。

有没有办法让类自动生成,所以我不需要lein compile每次都运行?我认为这就是:aotin theproject.clj所做的。

4

1 回答 1

1

使用 Leiningen,指定 :aot 设置。:all 是最简单的。

项目.clj

(defproject test-proj "0.1.0-SNAPSHOT"
  :main test-proj.core
  :aot :all
  :dependencies [[org.clojure/clojure "1.8.0"]])

如果需要,可以在数组中指定确切的命名空间,如下所示:

项目.clj

(defproject test-proj "0.1.0-SNAPSHOT"
  :main test-proj.core
  :aot [test-proj.core]
  :dependencies [[org.clojure/clojure "1.8.0"]])

然后是以下 lein 命令:

lein compile

将生成上面 :aot 设置中指定的字节码和 .class 文件。

核心.clj

(ns test-proj.core
    (:gen-class))

(defn -main[]
  (println test_proj.core)
  (println "Hello, World!"))

你想看到类似下面的东西:

NikoMacBook% lein compile 
Compiling test-proj.core

完成后,检查目标文件夹,其中包含正确的类文件,此处为 test_proj/core.class。

NikoMacBook% tree target 
target
├── classes
│   ├── META-INF
│   │   └── maven
│   │       └── test-proj
│   │           └── test-proj
│   │               └── pom.properties
│   └── test_proj
│       ├── core$_main.class
│       ├── core$fn__38.class
│       ├── core$loading__5569__auto____36.class
│       ├── core.class
│       └── core__init.class
└── stale
    └── leiningen.core.classpath.extract-native-dependencies

7 directories, 7 files

以下将运行 :main 命名空间,即 test-proj.core。

lein run 

将输出

NikoMacBook% lein run 
Compiling test-proj.core
Compiling test-proj.core
test_proj.core
Hello, World!

请注意,该类正在调用自身。另请注意,如果您不预先运行 lein compile ,它将自行运行。

于 2017-09-28T05:00:34.777 回答