2

I am having trouble using a Java interface from Clojure.

I have the folowing class: public class OpenAccess

which has a method: static Connection connect(String url)

where Connection is a interface: public interface Connection

In Java I would do this to setup a connection:

Connection conn = OpenAccess.connect(url);

I tried the following from Clojure but it doesn't work:

(defn connection [url]
  (let [oa (access.OpenAccess.)
    connection (reify access.Connection
             .....
(.connect oa connection)))

it errors with "IllegalArgumentException No matching method found: connect for class access.OpenAccess"

I can't figure out how to properly execute Java interfaces from Clojure.

1 Answer 1

3

Looks like a static call:

(defn connection [url]
  (OpenAccess/connect url))

And you would use it like this if you needed to type-hint it:

(let [^Connection conn (connection "http://foo")]
  // use your conn 
  )

You don't need the ^Connection but it will tell the compiler the type of the method invocations on conn which will avoid reflection.

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

1 Comment

It's generally better to type-hint the names in a let-binding, rather than the values, like (let [^Connection conn (foo ...)] ...). Most of the time, as here, that doesn't matter, but in particular if foo is a macro, your typehint will be silently ignored, as discussed in dev.clojure.org/jira/browse/CLJ-865.

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.