简体   繁体   中英

How do I call a Java static method with no arguments in Clojure?

I am trying to figure out how to call a static method with no arguments in Clojure. Two (bad) examples are (sun.misc.Unsafe/getUnsafe) and (Object/getClass) , both of which throw a CompilerException caused by a NoSuchFieldException .

Yes I know there is a simpler way to call getClass and I should not be using sun.misc.Unsafe at all - just wondering how to call a no-arg static method in Clojure in general.

Your examples don't seem to work, but the following does

(System/currentTimeMillis)
> 1398285925298

So that's the way to call a no-arg static method.

Object/getClass doesn't appear to be a static method. It's meant to be called on an object, not a class.

Getting at an Unsafe instance involves overcoming some access restrictions. The simplest way is to use reflection; see the Java Magic. Part 4: sun.misc.Unsafe blog post by Mykhailo Kozik for a description of this and other methods. Here's a Clojure snippet which does just that:

(let [f (.getDeclaredField sun.misc.Unsafe "theUnsafe")]
  (.setAccessible f true)
  (.get f nil))
;= #<Unsafe sun.misc.Unsafe@63124f52>

As pointed out by acomar and WolfeFan, getClass is not a static method -- it's an instance method declared by Object and therefore available on all objects:

(.getClass the-unsafe) ; the-unsafe obtained as above
;= sun.misc.Unsafe

As for the actual question, (Foo/meth) is the correct syntax for a no-argument static method call in Clojure.

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