0

I'm trying to call methods that take no arguments on a Java class, but when I do, I get reflection warnings saying that "reference to field [methodName] can't be resolved".

According to this the Clojure docs on Java interop (http://clojure.org/java_interop), "The instance member form works for both fields and methods." How can I tell it that I want a method? It seems to assume that since I'm not passing args that I want a field.

1
  • What does your code look like? in the off chance you are not wrapping the method in parens, I am sure java would have a similar complaint if you specified foo.bar instead of foo.bar() Commented Dec 8, 2014 at 3:01

2 Answers 2

2

If there are both fields and methods, then the (.member instance) form will invoke the method (which is more common). If you want to force access to the field, the (.-field instance) form will only retrieve the field value.

If you have an example that is not working as you expect, it would be helpful to see the code or error.

There are some circumstances where if the Clojure compiler cannot find the method (by an unknown instance class or parameter types), the error message will indicate it was looking for a field, but this is just an artifact of the order it's evaluating options. Sometimes turning on reflection warnings will help pinpoint the issue better.

Sign up to request clarification or add additional context in comments.

Comments

0

Here's an example. It creates a Java class - StringBuilder, initialised with a string. A method with no parameters - reverse - is then called on it and the results are converted to a String by calling the toString method.

user=> (def sb (java.lang.StringBuilder. "Hello World"))
;; #'user/sb
user=>  (.toString (.reverse sb))
;; "dlroW olleH"
user=>  (.toString (.reverse sb))
;; "Hello World"
user=>

A StringBuilder object is mutable so it retains its state, as a result, the second reverse rolls back the first one. This is not very Clojure like so it has to be used with caution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.