Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find implemented protocols in Clojure object?

Tags:

clojure

Is there a documented way to find which protocols are implemented by a Clojure object? The other way around (show for which classes a given protocol is extended) is easy: (extenders protocol).

like image 649
Maurits Rijk Avatar asked Jan 10 '11 21:01

Maurits Rijk


1 Answers

I ended up with the following implementation:

(defn protocol? [maybe-p]
  (boolean (:on-interface maybe-p)))

(defn all-protocols []
  (filter #(protocol? @(val %)) (ns-publics *ns*)))

(defn implemented-protocols [sym]
  (filter #(satisfies? @(val %) sym) (all-protocols)))

First it looks for all the symbols in the current namespace (you can of course extend this to all namespaces) whether they are protocol definitions or net (all-protocols). Next it looks for a given symbol if it satisfies one of these protocols.

The protocol? function uses the :on-interface key which isn't documented afaik, so this function is not portable.

like image 174
Maurits Rijk Avatar answered Oct 25 '22 04:10

Maurits Rijk