如何从 matlab 运行 clojure 脚本?

我尝试了以下操作:
用jdk 1.7运行matlab然后调用java

MATLAB_JAVA=/usr/lib/jvm/java-7-oracle/jre matlab

在matlab中,设置类路径并使用clojure编译器
javaaddpath([pwd '/lib/clojure-1.5.1.jar'])
import clojure.lang.RT

在这里我得到了错误:
Error using import
Import argument 'clojure.lang.RT' cannot be found or cannot be imported.

当我编写运行 clojure 的 java 类时,一切都从控制台运行,但不能从 matlab 运行。
请指教。

最佳答案

看起来这是 Clojure 不高兴从 Matlab 的“动态类路径”运行的问题。我在 OS X 10.9 上使用 Matlab R2014a 遇到了同样的错误,使用捆绑的 JVM 或 Java 1.7.0u51。但是,如果我通过将 clojure-1.5.1.jar 放在 Matlab 启动目录中的自定义 javaclasspath.txt 中来将 javaaddpathstatic() 添加到静态类路径中,那么 Clojure 类就会变得可见。

>> version -java
ans =
Java 1.7.0_51-b13 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
>> cloj = clojure.lang.RT
cloj =
clojure.lang.RT@77de6590

破解 Java 类路径

您使用 this answer 中的“类路径黑客”方法从 Matlab 命令行向静态类路径添加条目,而不必使用自定义 Matlab 设置。那里的答案涉及编写一个新的 Java 类,但您可以在纯 M 代码中执行等效操作。
function javaaddpathstatic(file)
%JAVAADDPATHSTATIC Add an entry to the static classpath at run time
%
% javaaddpathstatic(file)
%
% Adds the given file to the STATIC classpath. This is in contrast to the
% regular javaaddpath, which adds a file to the dynamic classpath.
%
% Files added to the path will not show up in the output of
% javaclasspath(), but they will still actually be on there, and classes
% from it will be picked up.
%
% Caveats:
% * This is a HACK and bound to be unsupported.
% * You need to call this before attempting to reference any class in it,
%   or Matlab may "remember" that the symbols could not be resolved.
% * There is no way to remove the new path entry once it is added.

parms = javaArray('java.lang.Class', 1);
parms(1) = java.lang.Class.forName('java.net.URL');
loaderClass = java.lang.Class.forName('java.net.URLClassLoader');
addUrlMeth = loaderClass.getDeclaredMethod('addURL', parms);
addUrlMeth.setAccessible(1);

sysClassLoader = java.lang.ClassLoader.getSystemClassLoader();

argArray = javaArray('java.lang.Object', 1);
jFile = java.io.File(file);
argArray(1) = jFile.toURI().toURL();
addUrlMeth.invoke(sysClassLoader, argArray);

因此,使用此 javaaddpath() 而不是 ojit_code,您的代码可能会起作用。

关于matlab - 如何从matlab运行clojure,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19625073/

10-14 18:00
查看更多