Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Java 17 record to Clojure map?

There is a standard function clojure.core/bean converting POJO to map:

class MyPojo{
  public String getFirst(){ return "abc"; }
  public int getSecond(){ return 15; }
}

IFn bean = Clojure.var("clojure.core", "bean")

var result = bean.invoke(new MyPojo())

// result => {:first = abc, :second = 15}

For Java 17 record classes this function would not work, because records do not follow POJO convention "get***" for properties.

Is there Clojure support for Java 17 record instances in the same manner?

like image 321
diziaq Avatar asked Jun 21 '26 15:06

diziaq


1 Answers

Java 16 introduces Class.getRecordComponents. So given an instance of a record, you can look up the record's class, and from there its record components. Each record component has a name and a getter Method, which you can use to look up the value of that component. You can put these pieces together to build an analogue of bean.

(defn record->map [r]
  (into {} (for [^java.lang.reflect.RecordComponent c (seq (.getRecordComponents (class r)))]
             [(keyword (.getName c))
              (.invoke (.getAccessor c) r nil)])))

If you're concerned about performance, the reflection in the body may be an issue. If you expect to call this function multiple times on records of the same type, you could pay up front to pre-compile a function that uses direct method calls instead of reflection. This sort of thing is one of the rare defensible use-cases for eval. Consider something like this:

(def beanerizer (memoize
  (fn [^Class c]
    (let [class-name (.getName c)
          arg (with-meta (gensym "r") {:tag class-name})]
      (eval
        `(fn [~arg]
           ~(into {} (for [^java.lang.reflect.RecordComponent comp (seq (.getRecordComponents c))]
              (let [field (.getName comp)]
                [(keyword field)
                 `(. ~arg ~(symbol field))])))))))))

It uses reflection when you call beanerizer, and uses eval (even more expensive!) to compile a function. But that compiled function uses no reflection, so calling it many times is as cheap as you could ask for.

If you find the eval/syntax-quote interleaving a little hard to read, here's an example of what function it evals. Given a record like the below, it compiles to a function whose definition is just a straightforward map:

defrecord MyRecord(int x, String name) {}

;; (beanerize MyRecord) compiles to:
(fn [^MyRecord r]
  {:x (. r x), :name (. r name)})
like image 150
amalloy Avatar answered Jun 23 '26 08:06

amalloy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!