I understand how protocols can be used to introduce new behaviour to existing classes, but is it possible for them (or any other Clojure mechanism) to introduce state to existing classes? More specifically, I would like to be able to associate a map with instances of a class that comes from a 3rd-party library.
Protocols are conceptually similar in Java Interfaces in that they don't concern themselves with state or representation at all, so I'm pretty sure you can't do it that way unless you store the state outside the object itself. You can however use the various other ways of extending (subclassing) classes in Clojure to do this, e.g. using a proxy
or with gen-class
. (see
http://clojure.org/java_interop#Java%20Interop-Implementing%20Interfaces%20and%20Extending%20Classes)
You can create a protocol with set-state
and get-state
functions. Then extend them to the classes you want, with an implementation built around a hashmap of some kind. You can't store the state in the foreign objects, but you can have your functions share a ref of a hashtable keyed by object. I think this solution may have a number of problems, like how do you detect when an object will be GCed and its state needs to be cleared as well? You can use a WeakReference or something, but it isn't trivial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With