Last active
November 30, 2016 16:19
-
-
Save christianromney/6c8175b7fab58f1efeae97c336fe51c0 to your computer and use it in GitHub Desktop.
A handy little Clojure utility function to print the members of an object.
This file contains hidden or 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
(defn inspect | |
"Reflects the members of an object and prints them. Returns the | |
number of members on the object. Constructors are labeled | |
with [ctor], public members are prefixed with +, private members are | |
prefixed with -, and static members are listed as Class/member. | |
Fields are annotated as fieldName : type, functions have a parameter | |
list enclosed in parentheses (param1, param2) followed by an arrow | |
-> and the return type. Varargs have an elipsis following the last | |
param (params...)." | |
[x] | |
(letfn [(shorten | |
[s] | |
(-> s clojure.core/name (clojure.string/split #"\.") last)) | |
(format-name | |
[{:keys [name flags declaring-class] :as data}] | |
(if-not (flags :static) | |
(shorten name) | |
(format "%s/%s" (shorten declaring-class) name))) | |
(format-return | |
[{:keys [type return-type]}] | |
(cond | |
return-type | |
(str " -> " return-type) | |
type | |
(str " : " type) | |
:else | |
" [ctor]")) | |
(format-params | |
[{:keys [flags parameter-types return-type]}] | |
(cond | |
(seq parameter-types) | |
(str "(" | |
(apply str (interpose ", " parameter-types)) | |
(if (flags :varargs) "..." "") | |
")") | |
return-type | |
"()" | |
:else | |
"")) | |
(format-visibility | |
[{:keys [flags]}] | |
(cond | |
(flags :public) | |
"+" | |
(flags :private) | |
"-" | |
:else | |
" ")) | |
(format-method | |
[{:keys [return-type parameter-types flags] :as data}] | |
(->> data | |
((juxt format-visibility | |
format-name | |
format-params | |
format-return)) | |
(apply str)))] | |
(let [type-name (str "Type: " (.getName (class x))) | |
methods (->> x clojure.reflect/reflect :members (map format-method) sort)] | |
(println type-name) | |
(println (apply str (repeat (count type-name) "-"))) | |
(doseq [m methods] | |
(println m)) | |
(count methods)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output for
(inspect (java.nio.file.Paths/get (java.net.URI. "file:///home/christian")))
: