How can I get the methods of a Java class from Clojure?
解决方案
[EDIT 2]
Per M Smith's comment below, this accomplishes the same but provides sorting by method name and only returns methods:
(print-table
(sort-by :name
(filter :exception-types (:members (r/reflect "foo")))))
[/EDIT 2]
[EDIT]
My original answer refers to Clojure 1.2, but things have changed with Clojure 1.3. This works without any reliance on Clojure's contrib libraries now:
(require '[clojure.reflect :as r])
(use '[clojure.pprint :only [print-table]])
(print-table (:members (r/reflect "foo")))
This provides a much more decoupled approach, with the reflect function providing all kinds of information on the argument passed in (in this case, a String "foo") and the print-table function taking any generic tabular data structure and pretty printing it as such.
[/EDIT]
I'd use the show function in the clojure.contrib.repl-utils namespace, which will print all static and instance members for an object (or class of an object). I require it like so:
(require '[clojure.contrib.repl-utils :as ru])
Here's an example using Joda Time:
(import 'org.joda.time.DateTime)
(ru/show DateTime)
(ru/show (DateTime.))
The first example demonstrates how you can simply pass a class to show, while the second demonstrates that you can pass an instance of the class as well.
This of course works for lots of Clojure items that are Java classes underneath. Here's an example of seeing all methods available to an instance of java.lang.String:
(ru/show "foo")