在Clojure中,如何动态使用java类? [英] In Clojure, how to use a java Class dynamically?

查看:196
本文介绍了在Clojure中,如何动态使用java类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Clojure中,如何使用存储在变量中的java类?



如何修复下面的代码?

 (def a java.lang.String)
(new a1); CompilerException java.lang.IllegalArgumentException:无法解析类名:a

为什么这个工作正常? / p>

 (def a str)
(a1)
/ pre>

解决方案

最优雅的解决方案是写 construct new 相同,但能够动态接收类:

  (defn construct [klass& args] 
(clojure.lang.Reflector / invokeConstructor klass(into-array Object args)))
(def a HashSet)
(construct HashSet' 2 3));有用!!!

此解决方案克服了 @ mikera 的答案(见评论)。



特别感谢 @MichałMarczyk ,让我意识到 invokeConstructor 回答我的另一个问题: Clojure:如何在函数内创建记录?



另一个选项是存储调用构造函数作为一个匿名函数。在我们的例子中:

 (def a#(String。%1))
(111); 111


In Clojure, how to use a java Class that is stored in a variable?

How should I fix the following code?

(def a java.lang.String)
(new a "1"); CompilerException java.lang.IllegalArgumentException: Unable to resolve classname: a

And why this one works fine?

(def a str)
(a "1")

解决方案

The most elegant solution is to write construct that does the same as new but is able to receive a class dynamically:

 (defn construct [klass & args]
    (clojure.lang.Reflector/invokeConstructor klass (into-array Object args)))
 (def a HashSet)
 (construct HashSet '(1 2 3)); It works!!!

This solution overcomes the limitation of @mikera's answer (see comments).

Special Thanks to @Michał Marczyk that made me aware of invokeConstructor answering another question of mine: Clojure: how to create a record inside a function?.

Another option is to store the call to the constructor as an anonymous function. In our case:

(def a #(String. %1))
(a "111"); "111"

这篇关于在Clojure中,如何动态使用java类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆