简体   繁体   中英

Calling java functions from Clojure

I can use (.toUpperCase "GOOD") in clojure, as "GOOD" is java string, and java string has toUpperCase method.

I also can use (java.io.File/separator) from clojure as a way of calling java functions.

But, why can't I call (java.lang/Object wait 3) or (java.lang.System/println "hi")?

  • Can't we use all the java functions from Clojure?
  • If not, is there any rule for calling them? If so, where are the reference for those functions?

You can use all Java functions from Clojure. See the great page on Clojure's Java interop .

In particular, you just need to get the syntax right depending on exectly what sort of Java construct you are dealing with, eg executing the println method on the static member "out" from java.lang.System:

(.println (System/out) "hi")

As the earlier poster noted, the two examples you give are just a little off:

(.wait (java.lang.Object.) 3) ;; this actually throws an IllegalMonitorStateException

(.println java.lang.System/out "hi")

Should work!

At first, Object.wait() function is not a static function, you should use as:

(.wait (java.lang.Object.) 3)

Second, Object.wait() function should be called after you get the lock. Otherwise, it will throw IllegalMonitorStateException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM