The Basics of Java Source Code Generation

I have a set of Java 5 source files with old Doclet tags, comments, and comments. And based on this, I would like to write a generator for another set of Java classes.

What is the best way to do this? And are there any good standalone libraries for parsing / generating code in Java? Any general knowledge in this area is appreciated.

So far I found them:

  • JaxME Reflection Java Source - Sounds good, but it doesn't seem to support annotations. Also since 2006, it was not produced.

  • Annogen - uses the JDK Doclet generator, which has some errors under 1.5 JDK. He also had no issues for a long time.

  • Javaparser - it seems good and quite recent, but it only supports the Visitor template for one class, that is, without the request mechanism as in the 2 above packages.

+7
java code-generation
source share
4 answers

Both NetBeans IDE and Eclipse JDT projects have significant Java code analysis / generation logic. I don’t know what their dependencies are (i.e. you can use them as stand-alone libraries), but, besides this, I would look at these two pretty well: it is unlikely that there will be a library for analyzing java code with more intensive development and more updated .

Update:

PMD may be of interest, as well as:

PMD scans the Java source code and looks for potential problems like:

* Possible bugs - empty try/catch/finally/switch statements * Dead code - unused local variables, parameters and private methods * Suboptimal code - wasteful String/StringBuffer usage * Overcomplicated expressions - unnecessary if statements, for loops that could be while loops * Duplicate code - copied/pasted code means copied/pasted bugs 

In addition, this blog article discusses various static code analysis tools.

+1
source share

If you only need to create syntactically correct Java code, check out the Codemodel .

+4
source share

I ended up using PMD. An example code is given below:

  final Java15Parser parser = new Java15Parser(); final FileInputStream stream = new FileInputStream("VehicleServiceType.java"); final Object c = parser.parse(new InputStreamReader(stream)); final XPath xpath = new BaseXPath("//TypeDeclaration/Annotation/NormalAnnotation[Name/@Image = 'WebService']", new DocumentNavigator()); for (final Iterator iter = xpath.selectNodes(c).iterator(); iter.hasNext();) { final Object obj = iter.next(); // Do code generation based on annotations... } 
+3
source share

it's not really a code generator, but if you need some bean-related functionality, apache beanutils is a time saver

http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.1/apidocs/org/apache/commons/beanutils/package-summary.html#dynamic

0
source share

All Articles