adding fields to proxy

30 views
Skip to first unread message

kyle smith

unread,
Jul 1, 2008, 3:42:39 PM7/1/08
to Clojure
I would like to create a macro that would let me add fields to a class
by generating accessors.

(proxy [class-and-interfaces] [args] [fieldone fieldtwo fieldthree]
(function1) (function2) (function3))


(let [fieldone] [fieldtwo] [fieldthree]
(proxy [class-and-interfaces] [args]
(function1)
(function2)
(function3)
(defn getfieldone [] fieldone)
(defn setfieldone [value] (set fieldone value))
(defn getfieldtwo [] fieldtwo)
(defn setfieldtwo [value] (set fieldtwo value))
(defn getfieldthree [] fieldthree)
(defn setfieldthree [value] (set fieldthree value))
))

The above is not valid clojure.

Rich Hickey

unread,
Jul 1, 2008, 9:01:51 PM7/1/08
to Clojure
proxy generates a single class for each unique superclass combination
and reuses that class for subsequent requests for that combination
rather than go through the overhead of a new class compilation each
call. It can do that because the generated class is just a thunk that
forwards methods to a map of Clojure fns. So, the things that look
like methods in a proxy call are not, and no fields or methods can be
added.

In short, proxy is not the right tool for this job. If you want to
create a class and add methods and even have some (immutable) state,
gen-class and friends offer many features.

If you really want to write a class with setFoo/getFoo functions on
top of mutable fields I recommend you use Java to do so.

Rich
Reply all
Reply to author
Forward
0 new messages