ClojureDocs

导航

命名空间

import

clojure.core

从 1.0 起可用 (来源)
  • (import & import-symbols-or-lists)
import-list => (package-symbol class-name-symbols*)
 For each name in class-name-symbols, adds a mapping from name to the
class named by package.name to the current namespace. Use :import in the ns
macro in preference to calling this directly.
5 Examples
user=> (import java.util.Date)
java.util.Date

user=> (def now (Date.))
#'user/now

user=> (str now)
"Tue Jul 13 17:53:54 IST 2010"
;; You can import multiple classes at once.
(import (java.util Date Calendar)
        (java.net URI ServerSocket)
        java.sql.DriverManager)
;; importing multiple classes in a namespace
(ns foo.bar
  (:import (java.util Date
                      Calendar)
           (java.util.logging Logger
                              Level)))
;; For cases when 'import' does not do it for you, i.e. "live-coding"
;; You can use the DynamicClassLoader, ClassReader and the Resolver.

(def dcl (clojure.lang.DynamicClassLoader.))

(defn dynamically-load-class! 
  [class-loader class-name]
  (let [class-reader (clojure.asm.ClassReader. class-name)]
    (when class-reader
      (let [bytes (.-b class-reader)]
        (.defineClass class-loader 
                      class-name 
                      bytes
                      "")))))

(dynamically-load-class! dcl "java.lang.Long")
(dynamically-load-class! dcl 'org.joda.time.DateTime)

;; From that point the dynamically loaded class can be
;; used by the Reflector to invoke constructors, methods and to get fields. 
(import [org.apache.commons.codec.digest DigestUtils])

(defn md5-hash [input] 
  (DigestUtils/md5Hex input))

(md5-hash "hello world!") 
;; fc3ff98e8c6a0d3087d515c0473f8677
See Also

Loads libs, skipping any that are already loaded. Each argument is either a libspec that identifie...

Added by gstamp

Like 'require, but also refers to each lib's namespace using clojure.core/refer. Use :use in the n...

Added by gstamp

Sets *ns* to the namespace named by name (unevaluated), creating it if needed. references can be ...

Added by gstamp
3 Notes
    By , created 14.4 years ago
    By , created 10.8 years ago

    import will also accept vectors instead of lists, but I would discourage folks from doing so:

    • It's undocumented.
    • Lists and vectors have different meanings for require, so there's precedent for making a distinction.
    • Lists have a distinguished first element, and so they indent more meaningfully here. :-P
    By , created 5.0 years ago

    You don't need to use import if you fully qualify the class name, e.g. (java.util.Date.).