clojurestatic-methodsclojure-java-interop

Clojure: call java static method/field via instance variable or string (not class name symbol)


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.


Solution

  • 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.