Aaron Bedra <aaron.be...@gmail.com> writes:

> user=> (defrecord MyRecord [a b c])
> user.MyRecord
> user=> (def rec (user.MyRecord. "one" "two" "three"))
> #'user/rec
> user=> (keys rec)
> (:a :b :c)

I guess the problem with that is that you need to have an instance of
the record before you can use `keys'.  And to create an instance, at
least you have to know the number of keys.

However, you can inspect the record's constructor using reflection:

  (-> MyRecord .getConstructors first .getParameterTypes)

This gets you an array of the record's parameter types.  It seems, that
the last 2 Object parameters are some internal stuff (metadata?), so the
array length - 2 is the arity.

  (-> MyRecord .getConstructors first .getParameterTypes)
  ==> 5 ;; so the record has 3 keys

If the record doesn't have fields hinted with primitive types, then
that's enough knowledge to create an instance.  If there are primitive
type hints, then the constructor has primitive type parameters you have
to match when calling it.

All in all, it seems there's everything you need to create a function
that creates a dummy instance of arbitrary (unknown) records that you
can query for its keys afterwards.

But maybe there's a better way... :-)

Bye,
Tassilo

> On 08/29/2011 12:54 PM, Razvan Rotaru wrote:
>> Hi,
>>
>> Assuming I have:
>>
>> (defrecord myrecord [:a :b :c])
>>
>> is there a way to get the list of keys from the record definition?
>>
>> Thanks,
>> Razvan
>>

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