Search code examples
clojure

How do I find implemented protocols in Clojure object?


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).


Solution

  • 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.