Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 438
Demi Avatar asked Feb 13 '23 03:02

Demi


2 Answers

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.

like image 51
cassandracomar Avatar answered Feb 15 '23 18:02

cassandracomar


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.

like image 31
Michał Marczyk Avatar answered Feb 15 '23 18:02

Michał Marczyk