Why do at runtime what you can do at compile time?
orginally this article is written by Ray (Google developer)
If GWT had a mantra, this would be it.
The GWT compiler deals with a closed world — no dynamic class loading, but it does permit deferment of binding decisions until compile time via a rule based mechanism that is part of the external GWT Module metadata. You can choose to replace a given type with other preauthored types, or, and here’s the important part: you can replace types with classes that are generated on the fly.
This is the compile time equivalent of what you would do at runtime with libraries like CGLIB or the JDK’s Proxy/Interceptor classes, and similar to Sun’s APT (Annotation Processing Tool), except that it’s all integrated into GWT and you don’t need to worry about running separate APT-passes.
The deferred binding mechanism is used heavily in GWT to replace standard implementations of browser widgets with quirky implementations for browsers with divergent behavior. GWT then compiles multiple permutations of your code base, running the binding rules separately for each browser. Thus, if you have rules to target 4 different browsers, you end up with GWT compiling 4 different code bases and producing 4 compiled outputs.
Why does it do this? Because the result is more optimal code. Otherwise, you would have to include all 4 Implementation subclasses in your main code base, and use runtime logic to dynamically call the appropriate target, e.g. “if(brokenDom) DOMImplIE.foo(), else… DOMImplStandard.foo()…” It shortens load time by only forcing your browser to load what is neccessary, and it shortens run time by removing another level of indirection. Finally, it permits the optimizer to actually inline the appropriate implementation directly into the call site.
GWT also uses compile time generation of Java code to implement many platform features. The most famous of course is the RPC/Serialization mechanism. Here, GWT takes an interface, such as MyServiceAsync, and generates an implementation of this class on the fly, which contains all of the logic needed to serialize non-primitive types, send them across the wire via XMLHttpRequest, invoke the RemoteService, deserialize the rule, and invoke the async handler. It is probably the most complex generator in GWT, but not the only one.
Internationalization and Localization are also handled by the generator mechanism. Instead of loading ResourceBundles at runtime, you instead pre-process them and turn them into an interface, with one method per property. GWT will then use a generator to fill in the implementation of this interface which returns the values that are in the property file when the corresponding method is invoked. And what if you don’t use some of the properties? The GWT compiler will remove any unused (uncalled) properties from the compiled application, and the number of HTTP requests is reduced because the locale data is bundled inline with your code.
Finally, truly the coolest and most innovative application of generators to date is the ImageBundle. In the world of 3D graphics programming, there is a technique called Texture Atlas, wherein you combine many textures into a single large texture, because on many graphics accelerators, changing pipeline state, such as binding a new texture before drawing geometry, is an expensive operation or may stall the pipeline. A program using texture atlases instead, binds one or more mondo-big textures, and simply uses texture coordinate manipulations to render portions of them as needed.
GWT 1.4 uses a similar technique to reduce load times and network traffic. With ImageBundle, like the I18N mechanism, you create an interface with a bunch of methods, one for each Image, as well as metadata annotations telling the GWT compiler which image file on disk you want returned by the method. Then, at compile time, the GWT compiler combines all of the images together into one large image file and generates an implementation class to return, essentially, the bounding box location of where each image is located within the overall atlas. Finally, when drawing the images, you just draw the same image (the large one) over and over, but use clipping rectangles to show only the part which corresponds to the image you need.
This reduces the number of HTTP requests drastically, speeds up startup time, and also centralizes media resources to a factory. The I18N and ImageBundle technique may even be combined to produce localized image bundles.
You’re starting to imagine the possibilities?
How about buttons rendered with drop-shadows? Rounded corners done at compile time? Object-relational mapping to Google Gears or serialized RowSets? Type-safe JSON wrappers?
The problem is, everytime I added a method to one of my GWT classes, I had to go write a bridge method for it, and as Chronoscope grew in size and complexity, I needed a more automatic, and safe, mechanism for exporting an external JS interface.
The first step is to decide what your generator is going to do. In my case, I want the generator to introspect one of my GWT classes, and generate an exported JS API with bridge methods.
What’s a bridge method?
Imagine you have the following GWT Class:
And you want to allow JS users to call the doSomethingUseful() function?
Today, you would use JSNI to export ‘bridge methods’ like so:
$wnd stands for the top-level window object, and by assigning to its doSomethingUseful property, you ensure GWT won’t obfuscate it. The JSNI call to Util.doSomethingUseful will be obfuscated however, thus the bridge method is neccessary to export the obfuscated symbol.
It gets more complicated if you want to bridge a non-static function, but here’s an example:
Which you may use as
As you can see, manual bridging gets tedious!
Generators to the rescue!
The first step in implementing a generator is to decide on a type that will be used to trigger the generator. So let’s introduce a new marker interface called ‘Exportable’. GWT also want the generated class to implement the Exporter interface, primarily, the export() method.
Here they are:
Simple eh? Next we’ll add the following line to our GwtExporter.gwt.xml module file:
What does this mean?
It means that when GWT.create() is invoked with a type that can be assigned to an Exportable, invoke the generator. That is, we want to write
and have it invoke the generator.
Specifying what gets exported
Next we have to decide on the rules for exporting. Which methods of an Exportable get exported? How do we control the generated JS namespace? etc. For now, let’s settle on the following logic — a method is exportable IF and ONLY IF:
- The class enclosing the method implements Exportable
- Metadata has determined it’s ok to export (more on this later)
Also, we need error checking. It is an error to export a method if any parameter or return type is not one of:
- a primitive type (int, float, etc)
- another Exportable
- an immutable JRE type (String, Integer, Double, etc)
GWT has its own form of annotations similar to JavaDoc/XDocLet tags. We will use this to control export policy. We will support two forms of export policy:
- White List
- By default, nothing exported.
- Each method to be exported must have a “@gwt.export” metadata annotation
- Black List
- Place “@gwt.export” on class itself (in JavaDoc for class)
- By default, all public methods exported
- Each method to be removed from export consideration tagged with “@gwt.noexport”
Finally, by default, the GWT Class’s package will be used as the JS’s namespace, (e.g. new $wnd.org.foo.bar.Employee). If you wish to use another package for the JS export, place “@gwt.exportPackage [package1.package2…]” on the class JavaDoc.
As an example:
and uses black-list policy to export getFirstName() but supress the export of getLastName(); Using white-list policy, you would write:
to achieve the same effect.
At this time, GWT are not considering function overloading.