在Clojure中,如何读取Java类实例的公共成员变量? [英] In Clojure how can I read a public member variables of an instance of a Java class?
问题描述
在Clojure中,如何读取Java类实例的公共成员变量?我想要类似的东西:
In Clojure how can I read a public member variables of an instance of a Java class? I want something like:
(. instance publicMemberName)
我也尝试过:
instance/publicMemberName
但这仅适用于静态方法
推荐答案
在Java中,类 java.awt.Point
具有公共字段 x
和 y
。请在此处查看Javadocs http://download.oracle.com /javase/6/docs/api/java/awt/Point.html 。
In Java, the class java.awt.Point
has public fields x
and y
. See the javadocs here http://download.oracle.com/javase/6/docs/api/java/awt/Point.html.
在Clojure中,点宏适用于字段和方法。这对我有用:
In Clojure the dot macro works for fields and methods. This worked for me:
user=> (let [p (new java.awt.Point 2 4)] (.x p))
2
编辑:以下操作也有效(注意点和p之间的空格):
The following also works (note the space between the dot and the p):
user=> (let [p (new java.awt.Point 2 4)] (. p x))
2
编辑:鉴于 java.awt.Point
具有方法 getX
和除了公共字段 x
和 y
之外的 getY
。所以去。首先,使Java类如下:
I decided to make a complete example given that java.awt.Point
has methods getX
and getY
in addition to public fields x
and y
. So here goes. First make a Java class like this:
public class C {
public int x = 100;
}
编译它
$ javac C.java
现在移动 C.class
到clojure目录中。接下来启动REPL,导入该类,并观察其工作:
Now move C.class
into your clojure directory. Next start the REPL, import the class, and watch it work:
$ java -cp clojure.jar clojure.main
Clojure 1.2.0
user=> (import C)
C
user=> (let [q (new C)] (. q x))
100
请注意其他方式也可以:
Note the other way works too:
user=> (let [q (new C)] (.x q))
100
这篇关于在Clojure中,如何读取Java类实例的公共成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!