Experience generating java source code?

Hello!

I’m considering to try to do code generation at work. Input is likely to be a JSON Schema.

I guess I could just write the .java file as a string. But I suspect that would be more error prone than generating a Java AST as some kind of data structure (if only java was homoiconic …). A quick search didn’t reveal any Clojure libraries for working Java AST as data.

Generated code should have:

  • appropriate private fields of the right type and with reasonable names
  • public getters
  • Gson annotations
  • an embedded builder class

Anyone done something similar? Suggestions?

Thanks!

You could always have a look at https://github.com/javaparser/javaparser and if it does what you need, drive it from clojure.

This was just something I bookmarked a while back - I haven’t used it, so this isn’t a recommendation exactly.

1 Like

Maybe http://www.jsonschema2pojo.org/ would work for you? It seems to me it meets the criteria and has plenty of options. I haven’t used it myself, though.

1 Like

Clojure itself uses this: https://asm.ow2.io/ except that generates bytecode, so .class files.

If you’re looking to generate Java source, string templates actually work pretty well and a lot of libs just do that. I’ve even used the cl-format function in the past for it :stuck_out_tongue_winking_eye:

Otherwise, like others have mentioned, JavaParser does what you ask, and there is also Spoon: http://spoon.gforge.inria.fr/ but both of them will take you longer to get going then string templating.

1 Like