Vladimir Protsenko
Vladimir Protsenko

Reputation: 1086

Does :gen-class is the only way to extend Java class in Clojure?

I have an unserializable third-party Java class A and I'd want to make it serializable to send over the net. Idea is to make new type SerializableA that extends A and implements Serializable. Then I'd want to write something like this:

(writeObject [this out] 
  (.writeObject out {:ff (. this 'ff) :gg (. this 'gg)}))

(readObject [this in] 
  (let [{ff :ff gg :gg} (.readObject in)]
    (set! (. this 'ff) ff)
    (set! (. this 'gg) gg)))

I am right that it could be done only with :gen-class in separate file? Or is there any other smarter solution, for example extending Serializable interface and attaching Serializable property to A class?

Upvotes: 2

Views: 110

Answers (1)

Alex Miller
Alex Miller

Reputation: 70239

Because these are "special methods" (not part of the actual Serializable interface) and because concrete inheritance is intentionally not provided in Clojure, the simplest path is probably to just write it in Java.

Leiningen makes it pretty easy to add both Java and Clojure source in your project and will compile the Java first, then make the classes available to your Clojure source.

Upvotes: 4

Related Questions