A Simple GWT Generator Example

9 April 2010No Comment

Generators allow the GWT coder to generate Java code at compile time and have it then be compiled along with the rest of the project into JavaScript. They are a sort of similar to T4 Templates in the .NET world. I don’t recommend Generators because you end up writing a lot of code in printLn()s which is sort of the opposite of “maintainability”. However, there were so few examples available I decided to post a simple one here just for the sake of it.

My Use Case is I want to generate a screen off of metadata and have it hooked to events written in Java code.

First you’ll need an interface that will be used to trigger the Generator. Anytime compiler sees this interface it’ll swap in a generated class.

Presto, it works. Run the sample, you’ll see a button added to the form, click it and you’ll get the hello world message.

There are a lot of issues with this. If you make a mistake, your code will break at compile time which is good, but since it’s breaking on a generated file, you’ll need to go digging in the TEMP folder to find the actual Java code that’s broken. For me this was located in C:\Documents and Settings\fs11782\Local Settings\Temp\ExampleScreenWrapper4091248644661218253.java
Exactly like T4 templates. Very messy.

The code is written out using strings, that makes it tough to maintain. It was very often necessary to import the generated file into the project to see what the issue was, then adjust the generator and then run it again.

Every time I did this Eclipse failed to recognize the changes and would only pick them up after a shutdown/restart of the IDE.

Generators in GWT: not recommended but there you are.

Let’s take a step back; GWT is supposed to solve the “problem” (false premise) of writing JavaScript. JavaScript is “bad” because it’s a dynamic language, loosely typed, interpreted and so on. Yet those are also advantages. Thinking back a few years I seem to recall a similar discussion between Lisp programmers and C++. By introducing Generators, I’ve actually lost all the perceived benefits of GWT, writing code out as a println() for example. I do get to write my code in Java but at a fairly high cost and high level of complexity with multiple layers of abstraction introduced into the solution.