Skip to content

Instantly share code, notes, and snippets.

@sunng87
Created November 20, 2015 10:04
Show Gist options
  • Select an option

  • Save sunng87/13700d3356d5514d35ad to your computer and use it in GitHub Desktop.

Select an option

Save sunng87/13700d3356d5514d35ad to your computer and use it in GitHub Desktop.
clojure: access private field/method via reflection
(defn invoke-private-method [obj fn-name-string & args]
(let [m (first (filter (fn [x] (.. x getName (equals fn-name-string)))
(.. obj getClass getDeclaredMethods)))]
(. m (setAccessible true))
(. m (invoke obj args))))
(defn private-field [obj fn-name-string]
(let [m (.. obj getClass (getDeclaredField fn-name-string))]
(. m (setAccessible true))
(. m (get obj))))
@shaunlebron
Copy link

shaunlebron commented Mar 4, 2026

As above, but with qualified methods instead of type hints:

(import '(java.lang.reflect Field))

(defn private-field [obj field-name]
  (->> (Object/.getClass obj)
       (iterate Class/.getSuperclass)
       (take-while some?)
       (some #(some-> (try (Class/.getDeclaredField % field-name)
                           (catch NoSuchFieldException _ nil))
                      (doto (Field/.setAccessible true))
                      (Field/.get obj)))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment