I want to take working Clojure source code files (.clj) and convert them into the e开发者_运维知识库quivalent java source code files (.java) automatically. I'm wondering what the best way to do this is or if it is even possible. The converted java source code would need to be acceptable enough.
Your best bet, as others have pointed out, would be to use a bytecode decompiler. You'll still need the clojure classes though. But, more importantly, if your goal is to generate Java code that needs to be handled by Java programmers, it is very unlikely that you'll succeed.
Clojure is not just "java with a different syntax". Its language constructs are so different from java that many things that are idiomatic Clojure will look very foreign in Java.
Even if your Java code would look more or less readable, your Java developers would get incredibly frustrated. They'd essentially still need to program Lisp but use Java syntax and very strange constructs: It'll be a mess.
If you're looking to use Clojure in a team of Java developers, I'd try to develop and package your Clojure code as a jar with a well defined java API. The Java developers would be happy, because it's just another java library, and you'll be happy because you'll write proper Clojure code.
I would try generating .class file from .clj and then decompiling it to .java with a decompiler e.g. JAD.
The Clojure debugging toolkit is an excellent tool for digging into compiled Clojure code and it demonstrates some of the ways Clojure's classes differ from classes produced from java source. It would be difficult for instance to write java code to represent Clojures closures for instance (though it's possible)
Clojure produces byte codes that cannot be produced by compiling any java program, so a general solution is not possible. Specifically Clojure nulls out arguments (in the calling frame) before making recursive calls. Since you are starting from source and not .class files you should be able to get close enough provided you don't try to guarantee that the java code will produce the exact same behavior. Clojure prevents some memory leaks in recursion that will be really hard to avoid in the equivalent java code.
"The purpose of this code is to null out the arguments to prevent 'holding the head' in case of a recursive function call. " from George Jahad's talk on decompiling clojure classes. http://georgejahad.com/clojure/clojureDecompiled.html
I am not intimately familiar with Clojure but note that you in general can read in a Lisp program and treat it as a datastructure, which is most likely better than handling the compiled Clojure code as this strongly depends on the Clojure runtime.
If this is for your own programs then you can probably live with a very small subset of full Clojure and that can you probably handle yourself with a small program generator.
精彩评论