gpt4 book ai didi

functional-programming - Clojure 代理是否总是调用 super.method()?

转载 作者:行者123 更新时间:2023-12-02 06:10:37 24 4
gpt4 key购买 nike

在使用 Clojure proxies 时, 传递给代理的 fns 应该覆盖现有方法,还是它们与 super.method() 一起调用?

在下面的代码中,RequestHandler.get() 与代理 get [] 一起被调用。

;see: http://github.com/paulosuzart/JTornado
(ns org.ctornadoweb)
(import '(org.jtornadoweb Web$RequestHandler))
(import '(org.jtornadoweb HttpServer Web$Application))


(let [myHandler (proxy [Web$RequestHandler] []
(get []
(.write "Hi CLJ"))
(post []
(.write "POST")))]

(.listen
(HttpServer.
(.add (Web$Application.) "/" (class myHandler))
false nil false) 8089))

编译/继承版本也是如此:

; Starts a JTornado HTTP Server and a sample RequestHandler.
; Bit verbose due to compilation directives. Recommendation is to generate
; a set of macros to hide this.
(ns org.ctornadoweb
; Compiled and implements a static main method to start the server
(:import (org.jtornadoweb HttpServer)
(org.jtornadoweb.Web$Application)
(org.jtornadoweb.Web$RequestHandler))
(:gen-class :prefix "server-"))

(gen-class
:name org.ctornadoweb.MyHandler
:extends org.jtornadoweb.Web$RequestHandler
:prefix "do")

(defn do-get [this]
"Handles the HTTP GET method"
(.write "hello clojure"))
(defn do-post [this]
"Handles the HTTP POST method"
(.write (.getArgument "name" "default" false)))


(defn server-main []
"main method"
(.listen
(org.jtornadoweb.HttpServer.
(.add (org.jtornadoweb.Web$Application.) "/" org.ctornadoweb.MyHandler)
false nil false) 8089))

;use (compile 'org.ctornadoweb)

跟踪显示代理被调用,然后是 super.get,什么抛出(默认情况下)异常。

HTTP 405: Method Not Allowed 
at org.jtornadoweb.Web$RequestHandler.get(Web.java:72)
at org.ctornadoweb.proxy$org.jtornadoweb.Web$RequestHandler$0.get(Unknown Source)

我试图找到一些关于 Clojure 代理的实际行为的词。有人可以提供帮助吗?

最佳答案

不,super 方法不会被自动调用,尽管您可以使用 proxy-super 显式调用它。

以下测试用例显示了它们应该正常工作:

user=> (def foo 
(proxy [java.util.ArrayList] []
(clear [] (println "not clearing"))))
#'user/foo
user=> (.size foo)
0
user=> (.add foo "hi")
true
user=> (.add foo "bye")
true
user=> (.size foo)
2
user=> (.clear foo)
not clearing
nil
user=> (.size foo)
2

如果 super.clear() 被调用,大小将显示为 0。

关于functional-programming - Clojure 代理是否总是调用 super.method()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3278072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com