Mercurial > lasercutter
view src/clojure/contrib/import_static.clj @ 10:ef7dbbd6452c
added clojure source goodness
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sat, 21 Aug 2010 06:25:44 -0400 |
parents | |
children |
line wrap: on
line source
1 ;;; import_static.clj -- import static Java methods/fields into Clojure3 ;; by Stuart Sierra, http://stuartsierra.com/4 ;; June 1, 20086 ;; Copyright (c) Stuart Sierra, 2008. All rights reserved. The use7 ;; and distribution terms for this software are covered by the Eclipse8 ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)9 ;; which can be found in the file epl-v10.html at the root of this10 ;; distribution. By using this software in any fashion, you are11 ;; agreeing to be bound by the terms of this license. You must not12 ;; remove this notice, or any other, from this software.16 (ns17 ^{:author "Stuart Sierra",18 :doc "Import static Java methods/fields into Clojure"}19 clojure.contrib.import-static20 (:use clojure.set))22 (defmacro import-static23 "Imports the named static fields and/or static methods of the class24 as (private) symbols in the current namespace.26 Example:27 user=> (import-static java.lang.Math PI sqrt)28 nil29 user=> PI30 3.14159265358979331 user=> (sqrt 16)32 4.034 Note: The class name must be fully qualified, even if it has already35 been imported. Static methods are defined as MACROS, not36 first-class fns."37 [class & fields-and-methods]38 (let [only (set (map str fields-and-methods))39 the-class (. Class forName (str class))40 static? (fn [x]41 (. java.lang.reflect.Modifier42 (isStatic (. x (getModifiers)))))43 statics (fn [array]44 (set (map (memfn getName)45 (filter static? array))))46 all-fields (statics (. the-class (getFields)))47 all-methods (statics (. the-class (getMethods)))48 fields-to-do (intersection all-fields only)49 methods-to-do (intersection all-methods only)50 make-sym (fn [string]51 (with-meta (symbol string) {:private true}))52 import-field (fn [name]53 (list 'def (make-sym name)54 (list '. class (symbol name))))55 import-method (fn [name]56 (list 'defmacro (make-sym name)57 '[& args]58 (list 'list ''. (list 'quote class)59 (list 'apply 'list60 (list 'quote (symbol name))61 'args))))]62 `(do ~@(map import-field fields-to-do)63 ~@(map import-method methods-to-do))))