On Fri, Mar 23, 2012 at 14:22, Alex Shabanov <[email protected]> wrote:
> Hi all,
>
> Is there any easy-to-use library for generating java code?
> I ended up writing simple function that takes strings and characters
> and prints them in formatted form (e.g. with tabs and newlines after
> braces).
> I really like compojure approach to build html page - is there any
> similar libraries exist for arbitrary code generation?
I've also looked for, but not found such a library.
I wrote a tool in Clojure which generates Java 5 enumerations from
data. The templating solution I settled on was to do this:
A template is a function which returns a template-result.
A template-result is a sequence of atoms and template-results.
An atom is a string, number, boolean, java.lang.Class, keyword, symbol or nil.
The result of running my code generator is thus a tree of atoms, which
I then flatten, remove the nils, and then convert the atoms:
- strings are just themselves
- keywords and symbols are their names
- java.lang.Class objects are the fully qualified name of the class
- booleans and numbers become java literals
Then concatenate the resulting strings.
It's odd, but it works, and has the advantage that templates
(functions) need not have side-effects and can be composed in
interesting ways.
e.g. (rough sketch):
(defn declare-field [name value]
["public final " (unbox (class value)) " " name " = " value ";"])
(defn declare-fields [name-val]
(interpose "\n"
(map delare-field (keys name-val) (vals name-val))))
(template-result->string
(declare-fields {:aNumber 1, :aBoolean false}))
Would produce something like:
public final long aNumber = 1;
public final boolean aBoolean = false;
This works OK for me, but it's really just a step up from raw printfs.
It doesn't understand anything about java syntax, so, handling
indentation -- for example -- is ad-hoc and brittle.
// ben
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en