Code generation: Java Beans to AS

If you have java backend that provides data to your flex application and you want to have matching data transfer object between java and flex you may end up with a lot of copy and paste from java to as.

For example you may have java bean that defines a user:

public class User {
    private String name;
    private int id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

When passing this object between java and flex (via webservices or fds) you want to have matching action script class, something like :

public class User {
  public var name:String;
  public var id:Number;
}

It looks like a perfect task for automation, given the amount of good tools for parsing and templating it would not take a lot of time to create a small application that can do transformation. I decided to use ANTLR v3.0 for parsing java code and StringTemplate for generating action script code. Both of these products are well integrated and easy to use.

ANTLR comes with java grammar, so all you need to do is to update grammar file to add actions that would capture information related to transformation, and later pass this info to StringTemplate to generate result code.

Here is binary that can be run from command line:

java -jar ASGen.jar c:/javacode/src data.A C:/ascode/src

you need to specify java src, full name of the java bean (including packages) and output folder for action script code.

But even better reason to use code generator is to fully automate the whole remote service layer. You can base it on java code (or wsdl for webservices or whatever else that allows to do mapping to flex code).

Here is the source code for java beans to as generator (it also includes code I use for service layer generations)


About this entry