ClojureDocs

Nav

命名空间

proxy

clojure.core

自 1.0 起可用 (源代码)
  • (proxy class-and-interfaces args & fs)
class-and-interfaces - a vector of class names
 args - a (possibly empty) vector of arguments to the superclass
constructor.
 f => (name [params*] body) or
(name ([params*] body) ([params+] body) ...)
 Expands to code which creates a instance of a proxy class that
implements the named class/interface(s) by calling the supplied
fns. A single class, if provided, must be first. If not provided it
defaults to Object.
 The interfaces names must be valid interface types. If a method fn
is not provided for a class method, the superclass method will be
called. If a method fn is not provided for an interface method, an
UnsupportedOperationException will be thrown should it be
called. Method fns are closures and can capture the environment in
which proxy is called. Each method fn takes an additional implicit
first arg, which is bound to 'this. Note that while method fns can
be provided to override protected methods, they have no other access
to protected members, nor to super, as these capabilities cannot be
proxied.
5 Examples
;; adding a mouse-pressed callback to a Swing component:

(defn add-mousepressed-listener
  [component f & args]
  (let [listener (proxy [MouseAdapter] []
                        (mousePressed [event]
                                      (apply f event args)))]
    (.addMouseListener component listener)
    listener))
;; BUG: proxy dispatches *only* on name, not arity:
user=> (let [p (proxy [java.io.InputStream] [] (read [] -1))]
         (println (.read p))
         (println (.read p (byte-array 3) 0 3)))

-1
ArityException Wrong number of args (4) passed to: core$eval213$fn  clojure.lang.AFn.throwArity (AFn.java:437)
;; You can, however, provide multiple-arity functions to get some support 
;; for overloading
user> (let [p (proxy [java.io.InputStream] []
          (read
            ([] 1)
            ([^bytes bytes] 2)
            ([^bytes bytes off len] 3)))]
  (println (.read p))
  (println (.read p (byte-array 3)))
  (println (.read p (byte-array 3) 0 3)))

1
2
3
nil
;; a simple example

(defn f [& i]
  (proxy [clojure.lang.ISeq][]
    (seq [] (sort i))
    (toString [] (apply str (interpose "-" i)))))

(seq (f 4 3 2 1))
;;=> (1 2 3 4)


(str (f 4 3 2 1))
;;=> "4-3-2-1"
;; usage of implicit 'this
(def prx (proxy [java.lang.Runnable] []
    (run 
      ([] (println "We can use this inside here" this) 1))))

(.run prx)
;;=>We can use this inside here #object[user.proxy$java.lang.Object$Runnable.....
See Also

When compiling, generates compiled bytecode for a class with the given package-qualified :name (wh...

Added by AtKaaZ

When compiling, generates compiled bytecode for an interface with the given package-qualified :nam...

Added by AtKaaZ

reify creates an object implementing a protocol or interface. reify is a macro with the following ...

Added by kumarshantanu
0 Notes
No notes for proxy