Clojure:无法找到静态字段

标签 clojure

给出以下代码:

(map Integer/parseInt ["1" "2" "3" "4"])

除非我换行,否则为什么会出现以下异常 Integer/parseInt在匿名函数中并手动调用它( #(Integer/parseInt %) )?

clojure.lang.Compiler$CompilerException: java.lang.RuntimeException: Unable to find static field: parseInt in class java.lang.Integer

最佳答案

关于 java interop 的文档说明如下:

The preferred idiomatic forms for accessing field or method members are given above. The instance member form works for both fields and methods. The instanceField form is preferred for fields and required if both a field and a 0-argument method of the same name exist. They all expand into calls to the dot operator (described below) at macroexpansion time. The expansions are as follows: ... (Classname/staticMethod args*) ==> (. Classname staticMethod args*) Classname/staticField ==> (. Classname staticField)

所以你应该记住,Class/fieldName只是获取静态字段的糖,既不是静态方法调用,也不是< strong>对静态方法的引用(java方法实际上并不是clojure函数),因此Integer class中没有静态字段parseInt,而(Class/fieldName arg) 调用静态方法,它们是两个完全不同的操作,使用类似的糖语法。

因此,当您执行 (map #(Integer/parseInt %) ["1""2""3""4"]) 时,它会扩展为

(map #(.Integer parseInt %) ["1""2""3""4"])

(您可以通过宏扩展轻松地自己看到它),

(map Integer/parseInt ["1""2""3"]) 扩展为

(map(.Integer parseInt)["1""2""3"])

当它尝试获取一个字段(您认为它正在获取对方法的引用)时,它会失败。

关于Clojure:无法找到静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35199808/

相关文章:

clojure - 什么是 fn*,它与 fn 有什么不同?

java - 如何将这个 Java 正则表达式转换为 Go 的正则表达式语法?

url - 如何在 Clojure 中下载带有 URL 查询的网页?

database - 我应该什么时候使用 Datomic?

concurrency - Clojure core.async go-blocks 什么时候有用?

emacs - 如何让Emacs,nrepl.el和Leiningen一起玩?

haskell - 做MapReduce的最佳功能语言?

data-structures - Clojure:如何使用整数序列而不是字母序列来实现 trie 树?

postgresql - 使用 clojure.java.jdbc/db-do-prepared 检查 uuid 是否存在于 PostgreSQL 表中失败

interface - 在 Clojure 中实现一个带有可变数量 args 的 Java 接口(interface)方法