Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure record: how to get hinted type given an attribute name

Tags:

clojure

record

I'm wondering is there a way to retrieve the type hinting associated with attributes declared with defrecord. e.g., if I have the following record definition:

(defrecord Foo [^Integer id ^String description])

I'd like to retrieve a map on Foo type that gives me the attributes and their hinted types. I know I can get a list of declared attributes through reflection:

(->> record .getDeclaredFields (remove #(java.lang.reflect.Modifier/isStatic (.getModifiers #))))

This does give me a list of declared fields, but their types are Object. I know Clojure is a dynamic language, but it'd be nice if the types are given back to me when I need them.

like image 386
EnToutCas Avatar asked Feb 21 '11 20:02

EnToutCas


1 Answers

The type hints are not kept anywhere. You can manage this information userself by writing a wrapper macro for defrecord which keeps the type information. You could e.g. generate a build function for the record type that enriches the instance with metadata on the fields:

(defrecord-hinted Foo [^Integer id ^String description])

; you could then acces the type information with
(->> (meta (make-Foo 42 "forty two")) 
     ::field-types
     :id) ; => java.lang.Integer.class
like image 170
ordnungswidrig Avatar answered Sep 17 '22 13:09

ordnungswidrig