On Jul 26, 12:52 pm, Shantanu Kumar <kumar.shant...@gmail.com> wrote:
> Use this function:
>
> (defn ^java.lang.reflect.Field get-field
>   "Return Field object"
>   [^Class class ^String field-name]
>   (let [f (.getDeclaredField class field-name)]
>     (.setAccessible f true)
>     f))
>
> > (let [o (Something.)]
> >   (set! (. o :id) 12)
> >   (set! (. o :name) "Impostor")
> >   o)
>
> ...as follows (it works even with private fields):
>
> (let [o (Something.)]
>   (.set (get-field "id")   o 12)
>   (.set (get-field "name") o "Impostor")
>   o)

Oops! this should be:

(let [o (Something.)]
  (.set (get-field Something "id")   o 12)
  (.set (get-field Something "name") o "Impostor")
  o)

>
> Hope this helps.
>
> Regards,
> Shantanu
>
> On Jul 26, 11:10 am, Petr Gladkikh <petrg...@gmail.com> wrote:
>
>
>
>
>
>
>
> > I am trying to construct java object and assign it's fields from a map.
> > That is given Java object of class Something { long id; String name; }
> > and Clojure map {:id 12, :name "Impostor"}
> > I would like to set fields of java object to respective values from map.
>
> > Now, this works
> > (let [o (Something.)]
> >   (set! (. o :id) 12)
> >   (set! (. o :name) "Impostor")
> >   o)
>
> > But as soon as I use some value to get field expression compiler
> > starts complaining "Invalid assignment target".
> > that is
> > (let [o (Something.)
> >        ff :id]
> >   (set! (. o ff) 12)
> >   o)
> > I do not understand why this problem occurs. Any variations that I
> > tried to made it work do not do the trick.
> > Including weird (or ridiculous) ones like (set! (. o (symbol (str ":"
> > (name ff))) 12)
>
> > I suspect that this has something to do with compiler that needs field
> > names at compile time but Clojure could use reflection for this...
>
> > Can anyone point to what is wrong here?
>
> > By the way is there already some function that allows to set fields of
> > an object from a map?
>
> > --
> > Petr Gladkikh

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to