Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I see the methods associated with an object in Clojure?

What function do I use, in Clojure, to see the methods of a Java object?

user=> (some-function some-java-object)
... lots of methods ...
like image 347
Matt Fenwick Avatar asked Nov 02 '11 19:11

Matt Fenwick


People also ask

How do you use a method on an object?

You also use an object reference to invoke an object's method. You append the method's simple name to the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.

Is Clojure object oriented?

Clojure is a functional lisp, reportedly not at all object-oriented, even though it runs on the JVM, a VM designed for an object oriented language. Clojure provides identical interfaces for iterating over lists and vectors by abstracting them to an interface called seq.


2 Answers

Use java reflection.

(.getClass myObject)

gets you the class. To get methods,

(.getMethods (.getClass myObject))

Which gives you an array of methods. You can treat that like a sequence; I'd probably put it into a vector, so:

(vec (.getMethods (.getClass myObject)))
like image 100
Rob Lachlan Avatar answered Oct 07 '22 19:10

Rob Lachlan


Since version 1.3, Clojure comes bundled with the clojure.reflect namespace. The function reflect in particular can be used to show all methods (and other information) for an object. It is not quite as convenient to use as show. On the other hand, it is much more general and it is quite easy to write your own version of show using reflect as a building block.

As an example, if you want to see all methods for String which returns a String:

user=> (use 'clojure.reflect)
user=> (use 'clojure.pprint)

user=> (->> (reflect "some object") 
            :members 
            (filter #(= (:return-type %) 'java.lang.String))
            (map #(select-keys % [:name :parameter-types])) 
            print-table)
like image 41
Jonas Avatar answered Oct 07 '22 20:10

Jonas