java - ClassCastException MyType 无法转换为 MyType?

标签 java clojure jvm clojure-java-interop counterclockwise

我在 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 无法转换为 MyProject.core.TestType。我做错了什么,还是这是一个错误?请注意,如果我从测试函数中删除类型注释,那么它只是:

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

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

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

最佳答案

当您重新定义类型(使用 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) 

关于java - ClassCastException MyType 无法转换为 MyType?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21254384/

相关文章:

java - 在Java中以最优化的方式比较Oracle的2个表之间的数据

java - Maven + TestNG 打印@DataProvider的参数

clojure - 为什么我们需要 ' in (require ' [...]]) 和 Clojure?

java - Java版本和JVM的区别到底在哪里?

java - 如何理解 "Every Class object contains a reference to the ClassLoader that defined it. "?

java - 如何使用 OWLAPI 从 owl 个体获取注释

java - 在不使用字符串资源的情况下,根据手机语言更改 TextView 文本

concurrency - 通过使用无锁算法,Clojure是否无锁?

clojure - Cascalog deffilterop 与纯 clojure

java - 来自 JVM 的用于跟踪目的的唯一 ID