clojure实现java类

为什么需要这么干?因为clojure可以调用java的类,但有时候这些java类需要你实现一个子类或者传递一个自定义的java对象作为参数,所以需要将clojure代码编译成java代码。

还记得之前提过的:gen-class么,在(ns...)中,使用(:gen-class),在(ns..)之外,应该用 (gen-class)

下面是一个例子, 文件MoveDailyAction.clj内容如下:

  1. (ns kafka2hdfs.MoveDailyAction 
  2.   (:import [org.apache.hadoop.fs FileSystem Path] 
  3.            [java.io.IOException] 
  4.            [java.text DateFormat SimpleDateFormat] 
  5.            [java.util.Date])) 
  6.  
  7. (gen-class 
  8. :name "kafka2hdfs.MoveDailyAction" 
  9. :implements [org.apache.storm.hdfs.common.rotation.RotationAction] 
  10. :state dest 
  11. :init init 
  12. :constructors {[String][]}) 
  13.  
  14. (defn -init 
  15.   [dest] 
  16.   [[] 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

猜你喜欢

转载自blog.csdn.net/cpongo3/article/details/50039527