Skip to content

Instantly share code, notes, and snippets.

@wjlroe
Created October 5, 2012 11:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wjlroe/3839414 to your computer and use it in GitHub Desktop.
Save wjlroe/3839414 to your computer and use it in GitHub Desktop.
Utility function for getting types of Java methods from Clojure (for debugging)
(defn method-spy
"Print out reflection info about a method."
[classname methodname]
(let [c (Class/forName classname)
all-methods (.getDeclaredMethods c)
matching-methods (filter #(= methodname (.getName %)) all-methods)
pr-col (fn [name info] (println (format "%24s: %s" name info)))]
(doseq [m matching-methods]
(println (.toGenericString m))
(pr-col "ReturnType" (.getReturnType m))
(pr-col "GenericReturnType" (.getGenericReturnType m))
(let [p-types (.getParameterTypes m)
gp-types (.getGenericParameterTypes m)
types (map vector p-types gp-types)
x-types (.getExceptionTypes m)
gx-types (.getGenericExceptionTypes m)
exceptions (map vector x-types gx-types)]
(doseq [type types]
(pr-col "ParamterType" (first type))
(pr-col "GenericParamterType" (second type)))
(doseq [exception exceptions]
(pr-col "ExceptionType" (first exception))
(pr-col "GenericExceptionType" (second exception)))))))
@wjlroe
Copy link
Author

wjlroe commented Oct 5, 2012

Example usage:

=> (method-spy "redis.clients.jedis.Jedis" "rpush")

public java.lang.Long redis.clients.jedis.Jedis.rpush(java.lang.String,java.lang.String)
              ReturnType: class java.lang.Long
       GenericReturnType: class java.lang.Long
            ParamterType: class java.lang.String
     GenericParamterType: class java.lang.String
            ParamterType: class java.lang.String
     GenericParamterType: class java.lang.String

@wjlroe
Copy link
Author

wjlroe commented Oct 5, 2012

Adapted from some Oracle doc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment