Java in Clojure, evaluation issue

Is there a detailed explanation of the results obtained when evaluating the following on the REPL.

(.PI Math)

gives

IllegalArgument Exception

while

(. Math PI)

estimated as

3.141592653589793
+3
source share
1 answer

An explanation is provided at http://clojure.org/java_interop .

user> (macroexpand '(.PI Math))
(. (clojure.core/identity Math) PI)

(identity Math)returns an object Classrepresenting the class Math. You are trying to access an instance with a name PIin this object Class, but it does not exist. (This is different from accessing a static element with a name PIin the class Math.) You would use this object Classonly to reflect or to pass the class to other methods as an object or those kinds of things.

user> (class (identity Math))
java.lang.Class
user> (.getName (identity Math))
"java.lang.Math"
user> (.getName Math)
"java.lang.Math"
user> (.getMethods Math)
#<Method[] [Ljava.lang.reflect.Method;@12344e8>
user> (vec (.getMethods Math))
[#<Method public static int java.lang.Math.abs(int)> #<Method public static long java.lang.Math.abs(long)> #<Method public static float java.lang.Math.abs(float)> ...]
user> (.getField Math "PI")
#<Field public static final double java.lang.Math.PI>
user> (.getDouble (.getField Math "PI") Math)
3.141592653589793

, , , Math/PI.

user> (macroexpand '(Math/PI))
(. Math PI)
user> Math/PI
3.141592653589793
user> (. Math PI)
3.141592653589793
+12

Source: https://habr.com/ru/post/1732898/


All Articles