Mercurial > lasercutter
comparison 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 |
comparison
equal
deleted
inserted
replaced
9:35cf337adfcf | 10:ef7dbbd6452c |
---|---|
1 ;;; import_static.clj -- import static Java methods/fields into Clojure | |
2 | |
3 ;; by Stuart Sierra, http://stuartsierra.com/ | |
4 ;; June 1, 2008 | |
5 | |
6 ;; Copyright (c) Stuart Sierra, 2008. All rights reserved. The use | |
7 ;; and distribution terms for this software are covered by the Eclipse | |
8 ;; 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 this | |
10 ;; distribution. By using this software in any fashion, you are | |
11 ;; agreeing to be bound by the terms of this license. You must not | |
12 ;; remove this notice, or any other, from this software. | |
13 | |
14 | |
15 | |
16 (ns | |
17 ^{:author "Stuart Sierra", | |
18 :doc "Import static Java methods/fields into Clojure"} | |
19 clojure.contrib.import-static | |
20 (:use clojure.set)) | |
21 | |
22 (defmacro import-static | |
23 "Imports the named static fields and/or static methods of the class | |
24 as (private) symbols in the current namespace. | |
25 | |
26 Example: | |
27 user=> (import-static java.lang.Math PI sqrt) | |
28 nil | |
29 user=> PI | |
30 3.141592653589793 | |
31 user=> (sqrt 16) | |
32 4.0 | |
33 | |
34 Note: The class name must be fully qualified, even if it has already | |
35 been imported. Static methods are defined as MACROS, not | |
36 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.Modifier | |
42 (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 'list | |
60 (list 'quote (symbol name)) | |
61 'args))))] | |
62 `(do ~@(map import-field fields-to-do) | |
63 ~@(map import-method methods-to-do)))) |