Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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))))
@csakoda

This comment has been minimized.

Copy link

@csakoda csakoda commented Feb 7, 2017

Thank you!

@ylgrgyq

This comment has been minimized.

Copy link

@ylgrgyq ylgrgyq commented Jun 22, 2017

调用 invoke 之前 args 是不是要转换为 array ?

@aaronblenkush

This comment has been minimized.

Copy link

@aaronblenkush aaronblenkush commented Nov 13, 2017

I had to wrap args into an Object array to make this work. Line 5:

(. m (invoke obj (into-array Object args)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment