Tuesday, June 17, 2008

GWT and Metawidget Part 2: Pluggability

Update: the APIs shown in this blog entry have changed slightly in newer releases of Metawidget. Specifically Layouts are now set as an object instance, not as a class. Please download the latest documentation from http://metawidget.org

The latest release of Metawidget adds supports for Google Web Toolkit (GWT) 1.5. This series of blogs explores the challenges that had to be overcome to acheive this.

Pluggability

Pluggability is everywhere in Metawidget: pluggable inspectors, pluggable layout managers, pluggable binding implementations, etc. etc. The usual way this is acheived is through code like...

metawidget.setLayoutClass( TableLayout.class );

...which, somewhere behind the scenes, ends up calling...

layoutClass.newInstance();

GWT, however, is a very different kind of Web framework: it compiles Java to JavaScript, and JavaScript doesn't support newInstance.

But! Using GwtMetawidget, you can plug in different implementations by calling setLayout (and also setBinding, setInspector, etc.)! How is this possible?

GWT supplies a powerful concept called Generators. With a bit of work, you can use Generators to do all sorts of things, including scanning a project's available classes and generating fragments of code that be inserted at runtime.

For example, you can scan all the classes that implement Layout, and then generate a function that says:

if ( givenClass.equals( TableLayout.class )) return new TableLayout();

What's really great is you can push all this into the framework (in our case, Metawidget) so that it becomes 'magic' to the application code.

How does this work in practice? See for yourself! The Metawidget download includes a pre-built sample application, addressbook-gwt.war, that showcases a GwtMetawidget using pluggable bindings at runtime to generate the UI. It's covered in detail in the reference guide.

0 comments: