Created
December 16, 2010 14:58
-
-
Save liquidz/743485 to your computer and use it in GitHub Desktop.
java static method convert to clojure function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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