简体   繁体   English

如何确保Clojure变量是正确的Java类型

[英]How to make sure a clojure variable is of the right Java type

java-code XSSFRow row = sheet.getRow(p); Java代码XSSFRow row = sheet.getRow(p);
clojure-code (def row (.getRow sheet p)) clojure代码(def row (.getRow sheet p))
How do we make sure that row is of type XSSFRow ? 我们如何确保该行是XSSFRow类型的?

Clojure is dynamically typed, so the type of a var/value is determined at runtime. Clojure是动态类型的,因此var / value的类型在运行时确定。

If you want to make sure a value is of a certain class, you could make the following assertion: 如果要确保某个值属于某个类,则可以进行以下声明:

(assert (= (class row) XSSFRow))

Or, more concisely (thanks to opqdonut): 或者,更简洁一些(感谢opqdonut):

(assert (instance? XSSFRow row))

This does not check for exact class, but for any superclass: 这不会检查确切的类,但会检查任何超类:

(instance? Object row) ;=> true

Notice that there is a way to specify type hints for the compiler using metadata. 注意,有一种方法可以使用元数据为编译器指定类型提示。 In some forms you can insert the following constructions: 在某些形式中,您可以插入以下构造:

(let [^String str-val (do-something)] ...)
(def ^double y)
(defn f [^int int-arg ^"[[I" 2d-int-array] ...)

note the ^type expression. 注意^type表达式。 This is shorthand for specifying one element of metadata, that is, :tag key in metadata map. 这是用于指定元数据元素的简写,即元数据映射中的:tag键。 Now the compiler can optimize the code, directly resolving calls to java methods instead of reflection now when it knows exact type of var. 现在,编译器可以优化代码,在知道var的确切类型时直接解决对java方法的调用,而不是现在进行反射。

There is an example on clojure.org: http://clojure.org/java_interop#Java%20Interop-Type%20Hints . clojure.org上有一个示例: http : //clojure.org/java_interop#Java%20Interop-Type%20Hints It suggests, and I think it is right, not to overuse type hints, since they just clutter the code and are generally not needed for adequate performance. 它表明,我认为是正确的,不要过度使用类型提示,因为它们只会使代码混乱,并且通常不需要适当的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM