Clojure deftype 在同一命名空间中调用函数会抛出“java.lang.IllegalStateException:尝试调用未绑定的 fn:”

2024-04-10

我将 Clojure 放入一个大量使用 Jersey 和注释的现有 Java 项目中。我希望能够利用之前工作中现有的自定义注释、过滤器等。到目前为止,我已经粗略地使用了 deftype 方法和 javax.ws.rs 注释,参见第 9 章Clojure 编程 http://www.clojurebook.com/.

(ns my.namespace.TestResource
  (:use [clojure.data.json :only (json-str)])
  (:import [javax.ws.rs DefaultValue QueryParam Path Produces GET]
           [javax.ws.rs.core Response]))

;;My function that I'd like to call from the resource.
(defn get-response [to]
  (.build
    (Response/ok
      (json-str {:hello to}))))

(definterface Test
  (getTest [^String to]))

(deftype ^{Path "/test"} TestResource [] Test
  (^{GET true
     Produces ["application/json"]}
  getTest
  [this ^{DefaultValue "" QueryParam "to"} to]
  ;Drop out of "interop" code as soon as possible
  (get-response to)))

正如您从注释中看到的,我想调用 deftype 之外但在同一命名空间内的函数。至少在我看来,这使我能够将 deftype 专注于互操作和连接到 Jersey,并将应用程序逻辑分开(更像是我想编写的 Clojure)。

但是,当我这样做时,我得到以下异常:

java.lang.IllegalStateException: Attempting to call unbound fn: #'my.namespace.TestResource/get-response

deftype 和命名空间有什么独特之处吗?


...有趣的是,我在这个问题上花费的时间直到我在这里询问之后才得到答案:)

看起来命名空间加载和 deftypes 已在这个帖子。 https://groups.google.com/forum/#!msg/clojure-dev/4CtSVWcD15A/shpMuyjMpxsJ正如我怀疑的那样,deftype 不会自动加载命名空间。正如帖子中所发现的,我可以通过添加如下要求来解决此问题:

(deftype ^{Path "/test"} TestResource [] Test
  (^{GET true
     Produces ["application/json"]}
    getTest
    [this ^{DefaultValue "" QueryParam "to"} to]
    ;Drop out of "interop" code as soon as possible
    (require 'my.namespace.TestResource) 
    (get-response to)))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Clojure deftype 在同一命名空间中调用函数会抛出“java.lang.IllegalStateException:尝试调用未绑定的 fn:” 的相关文章

随机推荐