functional programming - Manipulating java objects from clojure -


am new @ clojure , interact java objects using clojure. if have understood, 1 can reach interaction using defprotocol. concretely try following:

1- have following java class

package mytestspackage;  public class testobject {      private string lastname;     private string firstname;     private string age;      public testobject(string lastname, string firstname, string age) {         super();         this.lastname = lastname;         this.firstname = firstname;         this.age = age;     }      public string getname() {         return this.lastname;     }      public void setname(string name) {         this.lastname = name;     }      public string getfirstname() {         return this.firstname;     }      public void setfirstname(string vorname) {         this.firstname = vorname;     }      public string getage() {         return this.age;     }      public void setage(string age) {         this.age = age;     }  } 

2- create clojure protocol should allow me access instances of above java class testobject

(ns mytestspackage) (defprotocol test   (first-name [t])   (last-name [t])   (age [t])) 

now question is: where concretly implement methods defined in protocol , how use implementation pass testobject instances clojure side , access values first name, last name etc...

any appreciated. in advance.

regards, horace

if have understood, 1 can reach interaction using defprotocol.

no, you've got wrong. protocols intended allow things similar interfaces allow in plain java (though more powerful). can access java class without protocols. official clojure documentation on topic: http://clojure.org/java_interop

example:

(ns example   (:import mytestpackage.testobject))  ;; how call methods on java objects      (defn first-name [obj]   (.getfirstname obj))  (defn last-name [obj]   (.getname obj))  (defn age [obj]   (.getage obj))  (defn set-first-name [obj name]   (.setfirstname obj name))  (defn set-last-name [obj name]   (.setname obj name))  (defn set-age [obj age]   (.setage obj age))  ;; in repl  example => (let [x (testobject. nil nil nil)      ;; how create java objects                  x (new testobject nil nil nil)]  ;; these expressions equivalent               (println (first-name x))               (set-first-name x "name")               (println (first-name x))               (set-last-name x "last name")               (set-age x "23")               (println (last-name x))               (println (age x))) ;; outputs nil name last name 23 

please note code nothing more example intended introduce java interop. no means should write real programs that, if in clojure.


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -