【问题标题】:ClassCastException MyType cannot be cast to MyType?ClassCastException MyType 不能转换为 MyType?
【发布时间】:2014-01-21 09:44:07
【问题描述】:

我在 Clojure 中使用 deftype 时遇到了一个问题。如果我运行以下代码:

(defprotocol TestProt
  (geta [this])
  (getb [this]))

(deftype TestType [a b]
  TestProt
  (geta [this] a)
  (getb [this] b))

(defn test-function [^TestType a-testtype]
  (print (.geta a-testtype))) 

(def test-tt (TestType. 1 1))

(test-function test-tt)

然后编译器抛出:ClassCastException MyProject.core.TestType cannot be cast to MyProject.core.TestType。我做错了什么,还是这是一个错误?请注意,如果我从测试函数中删除类型注释,那么它只是:

(defn test-function [a-testtype]
  (print (.geta a-testtype))) 

然后代码工作正常,但我收到关于反射的警告(启用了warn-on-reflect),并且运行速度较慢,这违背了在我当前的用例中使用 deftype 的目的。

编辑:好的,代码在 repl 中工作,但当我使用 ctrl-alt-s 加载它时不起作用(我在 Eclipse 中通过逆时针运行它)。所以问题似乎出在 Eclipse 或逆时针。

【问题讨论】:

  • 在我这边无法重现。 Clojure 1.5.1
  • 我也是。不可重现。 Clojure 1.5.1
  • 我也在运行 1.5.1,但是在 Eclipse 中,通过逆时针,加载了 core.typed。我刚刚在 repl 中尝试过,它在那里工作,只是当我用 ctrl-alt-s 加载代码时就不行了。

标签: java clojure jvm clojure-java-interop counterclockwise


【解决方案1】:

当您重新定义类型(使用 deftypedefrecord)但在某处使用了先前存在的类时,会发生这种情况,在您的情况下,在类型提示中。

我无法重现您使用 CountercClockwise 的 CtrlAltS 描述的行为,但它确实以全新的方式评估以下表达式REPL,因此它可能有助于诊断您的具体情况。

(defprotocol TestProt
  (geta [this])
  (getb [this]))

(deftype TestType [a b]
  TestProt
  (geta [this] a)
  (getb [this] b))

(defn test-function [^TestType a-testtype]
  (print (.geta a-testtype)))

(def test-tt (TestType. 1 1))

(println :first (test-function test-tt))

;= :first 1

;; redefine the type...
(deftype TestType [a b]
  TestProt
  (geta [this] a)
  (getb [this] b))

;; ...and the test-tt var with the new version     
(def test-tt (TestType. 1 1))

(println :second (test-function test-tt))

;= ClassCastException user.TestType cannot be cast to user.TestType  user/test-function (NO_SOURCE_FILE:89) 

【讨论】:

    猜你喜欢
    • 2013-06-11
    • 1970-01-01
    • 2012-07-27
    • 2021-08-05
    • 1970-01-01
    • 2012-11-29
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多