[forge-dev] Generate Code with Forge

Paul Bakker paul.bakker.nl at gmail.com
Sun Oct 23 04:52:43 EDT 2011


Hi Rafael,

There are two things you need to do:
1) "understand" the Person class
2) generate new code


1)
You can use a command parameter to get the Person class: @Option(name = "class", required = true, type = PromptType.JAVA_CLASS) JavaResource classUnderTest

JavaResource is a rich file representation of the class. 
Now you can use the JavaSourceFacet to get information about the class itself:

JavaSourceFacet java = project.getFacet(JavaSourceFacet.class);
JavaSource<?> javaSource = classUnderTest.getJavaSource();

javaSource has methods such as getPackage() etc.

2)
Now you have to generate code. There are two ways to do this, depending on your needs.
The most elegant way is to use the "JavaParser" builder API:

JavaClass javaClass = JavaParser.create(JavaClass.class)
               .setPackage(entityPackage)
               .setName(entityName)
               .setPublic()
               .addAnnotation(Entity.class).getOrigin()
               .addInterface(Serializable.class);
Field<JavaClass> id = javaClass.addField("private Long id = null;"); 
….

My experience is that this works best for small classes. If you need to generate a lot of code it might be better to use a tempting framework such as Apache Velocity.
You can find an example of this in the code of the Arquillian plugin: https://github.com/forge/plugin-arquillian/blob/master/src/main/java/org/jboss/seam/forge/arquillian/ArquillianPlugin.java#L93

You can just add Velocity to your pom file and it will work.

If you have any more questions, let us know! What kind of plugin are you writing?

Paul Bakker


On Oct 23, 2011, at 2:26 AM, Rafael Pestano wrote:

> Hi everyone,
> 
> this is my first mail to this list and id like to congratulate the Forge team for their work.
> 
> my question is, what's the best way to generate .java, .xhtml files with forge?
> 
> Id like to write a plugin which would receive an entity class as parameter and generate some code on top of it, eg:
> 
> $ generate-service Person
> $ generate-controller Person
> $ generate-view Person
> 
> 
> Where Person is a domain object, is it possible with Forge? if yes, whats the best way?
> 
> 
> thanks in advance.
> 
> 
> 
> 
> -- 
> Att, 
> 
> Rafael M. Pestano
> 
> Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
> Graduando em Ciência da Computação UFRGS
> _______________________________________________
> forge-dev mailing list
> forge-dev at lists.jboss.org
> https://lists.jboss.org/mailman/listinfo/forge-dev

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.jboss.org/pipermail/forge-dev/attachments/20111023/81e69fb6/attachment.html 


More information about the forge-dev mailing list