In Clojure how can I read a public member variables of an instance of a Java class?

旧时模样 提交于 2019-12-23 09:37:11

问题


In Clojure how can I read a public member variables of an instance of a Java class? I want something like:

 (. instance publicMemberName)

I also tried:

instance/publicMemberName 

but this only works with static methods


回答1:


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.

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

EDIT: 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

EDIT: 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;
}

Compile it

$ javac C.java

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



回答2:


If your object follows Java bean convention of getFoo to access member field foo, and you only need read access (i.e. aren't going to be mutating your object), you can use bean. That'll give you an immutable Clojure map that mimics the object, and then you can use standard keyword accessors.

user> (bean (java.awt.Point. 1.0 2.0))
{:y 2.0, :x 1.0, :location #<Point java.awt.Point[x=1,y=2]>, :class java.awt.Point}

user> (:x *1)
1.0


来源:https://stackoverflow.com/questions/6647020/in-clojure-how-can-i-read-a-public-member-variables-of-an-instance-of-a-java-cla

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!