1

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.

1

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks... I figured that might be the case (I don't write Java). I guess i'll have to settle with... (condp = (class ev) FirstClass (FirstClass/someMethod) SecondClass (SecondClass/someMethod). Not exactly a solution if you don't know the full set of possible class names of an instance.
I'll mark this as the accepted answer for now, as it's a good enough reason for me to re-factor my code away from this pattern. But if someone has a macro/reflection hack, feel free to share it.
What are the other classes you're looking at that have a .getKeyText static method?
In this case the specific class is just used as an example. There wouldn't be other classes as far as I know that define the getKeyText method.
0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.