Skip to content

Instantly share code, notes, and snippets.

@flashingpumpkin
Created January 5, 2012 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flashingpumpkin/1567478 to your computer and use it in GitHub Desktop.
Save flashingpumpkin/1567478 to your computer and use it in GitHub Desktop.
Importing static methods / fields into defns and defs
(ns gltut.importer
(:import [java.lang.reflect Method Field]))
(defn get-methods
"Return all the methods on a class"
[#^Class cls]
(into [] (. cls getMethods)))
(defn get-fields
"Return all the fields on a class"
[#^Class cls]
(into [] (. cls getFields)))
(defn method-name
"Return the name of a given method"
[#^Method method]
(.getName method))
(defn field-name
"Return the name of a given field"
[#^Field field]
(.getName field))
(defn get-parameters
"Return a vector of types that this method takes in order of declaration."
[#^Method method]
(into [] (.getParameterTypes method)))
(defn get-cls-method
"Return the first method on a class matching a given name.
user=> (get-cls-method System \"currentTimeMillis\")"
[class the-method]
(first (filter #(= (method-name %) the-method)
(get-methods class))))
(defn get-cls-methods
"Return all methods on a class matching a given name.
user=> (get-cls-methods System \"currentTimeMillis\")"
[class the-method]
(filter #(= (method-name %) the-method) (get-methods class)))
(defn get-cls-field
"Return the field on a class matching the given name"
[class the-field]
(first (filter #(= (field-name %) the-field)
(get-fields class))))
(defmacro import-method
"Import public static methods on classes as functions into the current
namespace for later reuse.
user=> (import-method java.lang.Math sqrt my-sqrt)"
[class import-what import-as]
(let [the-class (. Class forName (str class))
the-method (get-cls-method the-class (str import-what))
tmp-params (into [] (map (fn [_] `arg#) (get-parameters the-method)))
params (or tmp-params [])]
`(defn ~import-as ~params
(. ~class ~import-what ~@params))))
(defmacro import-field
"Import a public static field from a class into the current namespace as
a def"
[class import-what import-as]
(let [the-class (. Class forName (str class))]
`(def ~import-as (. ~class ~import-what))))
(import-method java.lang.System currentTimeMillis millis)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment