aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorStuart Sierra <mail@stuartsierra.com>2008-06-01 16:37:43 +0000
committerStuart Sierra <mail@stuartsierra.com>2008-06-01 16:37:43 +0000
commit7d207c2ca78fd9e3e30ec20a61b0372c1beaa705 (patch)
tree54a0b8651bd912b285327338202fab982cc84735
parente3282d82bc43ce64b12668dc7dedce4eca89363a (diff)
Added import-static.clj
-rw-r--r--import-static.clj60
1 files changed, 60 insertions, 0 deletions
diff --git a/import-static.clj b/import-static.clj
new file mode 100644
index 00000000..b26132e9
--- /dev/null
+++ b/import-static.clj
@@ -0,0 +1,60 @@
+;;; import-static.clj -- import static Java methods/fields into Clojure
+
+;; by Stuart Sierra, http://stuartsierra.com/
+;; June 1, 2008
+
+;; Copyright (c) 2008 Stuart Sierra. All rights reserved. The use and
+;; distribution terms for this software are covered by the Common
+;; Public License 1.0 (http://www.opensource.org/licenses/cpl1.0.php)
+;; which can be found in the file CPL.TXT at the root of this
+;; distribution. By using this software in any fashion, you are
+;; agreeing to be bound by the terms of this license. You must not
+;; remove this notice, or any other, from this software.
+
+
+
+(clojure/in-ns 'import-static)
+(clojure/refer 'clojure)
+
+(defmacro import-static
+ "Imports the named static fields and/or static methods of the class
+ as (private) symbols in the current namespace.
+
+ Example:
+ user=> (import-static java.lang.Math PI sqrt)
+ nil
+ user=> PI
+ 3.141592653589793
+ user=> (sqrt 16)
+ 4.0
+
+ Note: The class name must be fully qualified, even if it has already
+ been imported. Static methods are defined as MACROS, not
+ first-class fns."
+ [class & fields-and-methods]
+ (let [only (set (map str fields-and-methods))
+ the-class (. Class forName (str class))
+ static? (fn [x]
+ (. java.lang.reflect.Modifier
+ (isStatic (. x (getModifiers)))))
+ statics (fn [array]
+ (set (map (memfn getName)
+ (filter static? array))))
+ all-fields (statics (. the-class (getFields)))
+ all-methods (statics (. the-class (getMethods)))
+ fields-to-do (set/intersection all-fields only)
+ methods-to-do (set/intersection all-methods only)
+ make-sym (fn [string]
+ (with-meta (symbol string) {:private true}))
+ import-field (fn [name]
+ (list 'def (make-sym name)
+ (list '. class (symbol name))))
+ import-method (fn [name]
+ (list 'defmacro (make-sym name)
+ '[& args]
+ (list 'list ''. (list 'quote class)
+ (list 'apply 'list
+ (list 'quote (symbol name))
+ 'args))))]
+ `(do ~@(map import-field fields-to-do)
+ ~@(map import-method methods-to-do))))