Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top