Skip to content

Instantly share code, notes, and snippets.

@liquidz
Created December 16, 2010 14:58
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 liquidz/743485 to your computer and use it in GitHub Desktop.
Save liquidz/743485 to your computer and use it in GitHub Desktop.
java static method convert to clojure function
(ns jstatic
(:require
[clojure.contrib.string :as st]
[clojure.contrib.seq :as se]
)
(:import [java.lang.reflect Method])
)
(defn get-methods [#^Class klass, name]
(filter #(= name (.getName %)) (.getMethods klass))
)
(defn list->object-array [ls]
(let [arr (object-array (count ls))]
(doseq [[i x] (se/indexed ls)] (aset arr i x))
arr
)
)
(defn invoke-method [#^Method method, #^Objet obj, args]
(try
(.invoke method obj (list->object-array args))
(catch Exception e nil)
)
)
(defn make-static-method-fn [klass method-name]
(let [methods (get-methods klass method-name)
arities (map #(count (.getParameterTypes %)) methods)
arity-map (apply hash-map (interleave arities methods))
]
(fn [& args]
(invoke-method (get arity-map (count args)) nil args)
)
)
)
(defmacro static-method->fn [static-method]
(let [[klass method-name] (st/split #"/" (str static-method))
klass-symbol (symbol klass)]
`(make-static-method-fn ~klass-symbol ~method-name)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment