Clojure:无法找到静态字段 [英] Clojure: Unable to find static field

查看:70
本文介绍了Clojure:无法找到静态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

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

为什么我得到以下异常,除非我包装了 Integer / parseInt 在匿名函数中并手动调用(#(Integer / parseInt%))?

Why do I get the following exception unless I wrap Integer/parseInt in an anonymous function and call it manually (#(Integer/parseInt %))?

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


推荐答案

有关Java interop的文档中的内容如下:

the documentation on java interop says the following:


上面给出了访问字段或方法成员
的惯用形式。实例成员表单适用于字段和
方法。 instanceField形式是字段的首选格式,并且如果同时存在一个字段和一个名称相同的0参数方法,则需要
。它们
都在
宏扩展时间扩展为对点运算符的调用(如下所述)。扩展如下:
...
(Classname / staticMethod
args *)==>(。Classname staticMethod args *)Classname / staticField ==>
(。类名staticField)

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 只是用于获取静态字段,静态方法调用引用静态方法的糖(java方法实际上不是clojure函数) ,因此在 Integer类中没有静态字段 parseInt ,而(Class / fieldName arg )调用静态的方法,它们是两个完全不同的操作,使用的是类似甜心的语法。

so you should remember, that Class/fieldName is just a sugar for getting a static field, neither static method call, nor reference to the static method (java method is not a clojure function really), so there is no static field parseInt in Integer class, while (Class/fieldName arg) calls a static method, they are two totally different operations, using the similar sugary syntax.

所以当您可以(map#(Integer / parseInt%)[ 1 2 3 4])它会扩展为

so when you do (map #(Integer/parseInt %) ["1" "2" "3" "4"]) it expands to

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

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

(you can easily see it yourself with macroexpansion),

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

(地图(。 Integer parseInt)[ 1 2 3])

尝试获取字段时失败(您可以认为正在获得对方法的引用)。

It fails when it is trying to get a field (which you think is getting a reference to a method).

这篇关于Clojure:无法找到静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆