为什么需要这么干?因为clojure可以调用java的类,但有时候这些java类需要你实现一个子类或者传递一个自定义的java对象作为参数,所以需要将clojure代码编译成java代码。
还记得之前提过的:gen-class么,在(ns...)中,使用(:gen-class),在(ns..)之外,应该用 (gen-class)
下面是一个例子, 文件MoveDailyAction.clj内容如下:
- (ns kafka2hdfs.MoveDailyAction
- (:import [org.apache.hadoop.fs FileSystem Path]
- [java.io.IOException]
- [java.text DateFormat SimpleDateFormat]
- [java.util.Date]))
- (gen-class
- :name "kafka2hdfs.MoveDailyAction"
- :implements [org.apache.storm.hdfs.common.rotation.RotationAction]
- :state dest
- :init init
- :constructors {[String][]})
- (defn -init
- [dest]
- [[] dest])
(ns kafka2hdfs.MoveDailyAction
(:import [org.apache.hadoop.fs FileSystem Path]
[java.io.IOException]
[java.text DateFormat SimpleDateFormat]
[java.util.Date]))
(gen-class
:name "kafka2hdfs.MoveDailyAction"
:implements [org.apache.storm.hdfs.common.rotation.RotationAction]
:state dest
:init init
:constructors {[String][]})
(defn -init
[dest]
[[] dest])
这个类名叫MoveDailyAction,实现了RotationAction接口,有一个不可变的公有成员变量dest, 有一个init成员函数会在构造函数内部被调用。构造函数不需要实现,只需要声明参数形式。
具体可以参考下面两篇文档:
http://clojure.github.io/clojure/clojure.core-api.html#clojure.core/gen-class
http://kotka.de/blog/2010/02/gen-class_how_it_works_and_how_to_use_it.html