简体   繁体   中英

How to cast a Java class instance to Object[] in Clojure

I am using a JDBC library that implements its own Array class. In order to work with said Array they cast it to Object[].

https://github.com/housepower/ClickHouse-Native-JDBC/blob/master/src/test/java/com/github/housepower/jdbc/QueryComplexTypeITest.java#L120

I am using Clojure and can't figure out how to cast that class to the Java Array.

(vec (.getArray results "array-row"))
Unable to convert: class com.github.housepower.jdbc.ClickHouseArray to Object[]

Isn't that Java code is calling the .getArray method, and casting the results to an Object[] array, not the other way around? Looking at the source of com.github.housepower.jdbc.ClickHouseArray it seems to extend java.sql.Array via com.github.housepower.jdbc.wrapper.SQLArray which is not an Object[] . Right?

Clojure will just do runtime reflection to resolve a method on an object so you shouldn't need to worry about casting. There might be more information in the exception you're getting? Try using *e to get at the last exception in the REPL. If you could post a more complete test case, we might get a better idea of the problem?

I believe you can try to iterate that array and compose the result manually:

(let [array (.getArray results "array-row")]
  (for [item array]
    (turn-item-into-a-map item)))

or maybe just

(mapv turn-item-into-a-map jdbc-array)

In case you don't want to convert items, use identity function.

Even if such an array doesn't support iteration, you still can do that accessing its items by an index in loop/recur:

(let [array (get-jdbc-array...)
      size (.count array)]
  (loop [i 0
         result []]
    (if (= i size)
      result
      (let [item (.get array i)]
        (recur (inc i) (conj result item))))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM