Java Code Generation – How to Generate Code from Class Diagram

algorithmsclass-diagramjava

I'm on the way developing a Java application where user can provide a class diagram and get the corresponding Java code.

I don't know how can I let the user interactively draw a class diagram in Java. I am currently getting the required parameters like attributes, functions directly from the user, and then I render a class diagram for him. I show the class diagram on a jdialog.But when it comes to multiple class diagrams, it screws me. Is there a better way to do this?

This is an example of a class diagram, I need to generate this from a Java program, given the values and relationship.

enter image description here

Best Answer

First point: this is fairly non-trivial. Second point: the fact that the Java environment makes the Java compiler directly available will help a lot in implementing this. I believe you should be able to collect most (all?) the information you need by walking the AST with the compiler tree API. At least from the looks of things, the part you'll care the most about will be the ClassTree interface. So, the basic idea would be to create your tree visitor, walk the tree, and collect information about the ClassTree objects you find.

Once you've collected the information, it becomes mostly a matter of drawing a nicely formatted result. If you have some funds available, I've heard good things about yFiles for Java (I should also mention that the same company's yWorks UML Doclet is supposed to do nearly what you're talking about, but from JavaDac comments rather than the source itself). There are, as you'd expect, lots of alternatives to that as well. I don't know enough about most (any?) of them to comment further on them though (I did use GraphViz once, but so long ago that I don't remember much, and what little I might remember is probably obsolete anyway).

Related Topic