1
votes

I can do the following and it works...

=> (. java.awt.event.KeyEvent getKeyText 10)
"Enter"

But, I have an instance of java.awt.event.KeyEvent called ev. For example,

=> (class ev)
java.awt.event.KeyEvent

I want to call the method like this instead (but, this produces an error):

=> (. (class ev) getKeyText 10)
No matching method getKeyText found taking 1 args for class java.lang.Class

Is it possible to call a static method from an instance?

I have read the docs and searched stack overflow. The question here is not the same.

2
I may have found a duplicate question but i'll have to read the answers there... stackoverflow.com/questions/2852133/… - Joel M

2 Answers

1
votes

Just like in Java, you can only call static methods directly if you know at compile time what method of what class you want to call. Otherwise you need to use reflection on the Class object to find method handles.

0
votes

Here is an attempt using the MethodHandle API.

(ns playground.static-method-handle
  (:import [java.lang.invoke MethodType MethodHandles]))

;; Get a MethodType instance that encodes the shape of the method (return type and arguments)
(def getKeyText-method-type (MethodType/methodType String Integer/TYPE))

(defn call-getKeyText-on-class [cl key-code]
  (let [lu (MethodHandles/lookup)
        h (.findStatic lu cl "getKeyText" getKeyText-method-type)]
    (.invokeWithArguments h [(int key-code)])))

and we use it like this:

(call-getKeyText-on-class KeyEvent 10)
;; => "Enter"