narocath
narocath

Reputation: 65

Java interface to Clojure with proxy

I am new to Clojure and I am trying to implement a Java interface to Clojure. Specifically this code

import javax.print.*;

class Test {

    public static void main (String [] args)
    {
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        System.out.println("Number of print services: " + printServices.length);

        for (PrintService printer : printServices)
            System.out.println("Printer: " + printer.getName()); 
    }
}

The PrintService is an interface and the PrintServiceLookup a constaructor class. I am confused on how to use reify and proxy. My goal is to get the installed printers on my system. Can anyone explain with an example on how to use reify or proxy? From the documendation I understand that I must load the interface and then the methods I want to use, but I can't make it work. From Java perspective as I understand it, I must get an object from PrintServiceLookup.lookupPrintServices() and apply to it the getName function from PrintService interface and then to print it. My try till now

(defn print-serv []
  (let [printS (proxy [PrintService PrintServiceLookup] []
       (getName [])
                 (lookupPrintServices [])
    )]
    (.println (System/out) (.getName printSe))
    )

    )

I am pretty sure is all the way wrong but I can't understand how really reify and proxy work, if anyone could expain it to me better I would be grateful!

Upvotes: 0

Views: 253

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45726

The Java code you posted doesn't implement an interface. It looks like you're just trying to call a static method and iterate over the result:

(let [printers (PrintServiceLookup/lookupPrintServices nil nil)]
  (println "Number of print services:" (count printers))

  (doseq [^PrintService p, printers]
    (println (.getName p)))

The doseq loop can also be written simply as:

(doseq [p printers]
  ...)

I just included the ^PrintService type hint for completeness.

Also note, you don't have to write the full (.println (System/out) ...). Clojure has the println shortcut.

Upvotes: 2

Related Questions