[英]How can I cast a Java class in Clojure?
I would like to cast a clojure Java object (assigned with let*) to another Java class type. 我想将一个clojure Java对象(用let *赋值)转换为另一个Java类类型。 Is this possible and if so then how can I do this?
这是可能的,如果可以的话,我该怎么做?
Update: Since I posted this question I have realised that I do not need to cast in Clojure as it has no concept of an interface, and is more like Ruby duck typing. 更新:自从我发布这个问题后,我意识到我不需要使用Clojure,因为它没有接口的概念,而且更像是Ruby duck typing。 I only need to cast if I need to know that an object is definitely of a certain type, in which case I get a ClassCastException
如果我需要知道某个对象肯定属于某种类型,我只需要强制转换,在这种情况下我得到一个ClassCastException
There is a cast
function to do that in clojure.core
: 有一个
cast
功能做,在clojure.core
:
user> (doc cast)
-------------------------
clojure.core/cast
([c x])
Throws a ClassCastException if x is not a c, else returns x.
By the way, you shouldn't use let*
directly -- it's just an implementation detail behind let
(which is what should be used in user code). 顺便说一句,你不应该直接使用
let*
- 它只是let
后面的一个实现细节(应该在用户代码中使用)。
Note that the cast
function is really just a specific type of assertion. 请注意,
cast
函数实际上只是一种特定类型的断言。 There's no need for actual casting in clojure. 在clojure中不需要实际的铸造。 If you're trying to avoid reflection, then simply type-hint:
如果你试图避免反射,那么只需输入提示:
user=> (set! *warn-on-reflection* true)
true
user=> (.toCharArray "foo") ; no reflection needed
#<char[] [C@a21d23b>
user=> (defn bar [x] ; reflection used
(.toCharArray x))
Reflection warning, NO_SOURCE_PATH:17 - reference to field toCharArray can't be resolved.
#'user/bar
user=> (bar "foo") ; but it still works, no casts needed!
#<char[] [C@34e93999>
user=> (defn bar [^String x] ; avoid the reflection with type-hint
(.toCharArray x))
#'user/bar
user=> (bar "foo")
#<char[] [C@3b35b1f3>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.