4

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.

1
  • 2
    Object/getClass is not a static method. Call it on an object. Commented Apr 23, 2014 at 20:33

2 Answers 2

5

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.

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

Comments

3

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.

1 Comment

I know about the access restrictions, but I was expecting a SecurityException, not a NoSuchFieldException.

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.