How do I call clojure macros from Java?
•
Java
Did you call the clojure macro from Java?
This is what I am trying to do:
RT.var("clojure.core","require").invoke(Symbol.create("clojure.contrib.prxml"));
Var prxml = RT.var("clojure.contrib.prxml","prxml");
Var withOutStr = RT.var("clojure.core","with-out-str");
String stringXML = (String) withOutStr.invoke((prxml.invoke("[:Name \"Bob\"]")));
Prxml writes * out * by default, which is why I need to wrap macros with - out STR that returns a string
I received this error:
[java] java.lang.IllegalArgumentException: Wrong number of args (1) passed to: core$with-out-str [java] at clojure.lang.AFn.throwArity(AFn.java:437) [java] at clojure.lang.RestFn.invoke(RestFn.java:412) [java] at clojure.lang.Var.invoke(Var.java:365) [java] at JavaClojure.xml.main(UnkNown Source)
Solution
You have to scroll by yourself with outstr
class YourClass {
static final Var withBindings = RT.var("clojure.core","with-bindings*");
static final Var list = RT.var("clojure.core","list*");
static final Var out = RT.var("clojure.core","*out*");
static final Var prxml = RT.var("clojure.contrib.prxml","prxml");
static String withOutStr(IFn f,Object args...) {
StringWriter wtr = new StringWriter();
withBindings.applyTo(list.invoke(RT.map(out,wtr),f,args));
return wtr.toString();
}
...
String stringXML = withOutStr(prxml,"[:Name \"Bob\"]");
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
