BT

Google Introduces GWT Overlay Types

by R.J. Lorimer on Aug 03, 2008 |
The Google Web Toolkit team has posted an article on GWT overlay types as part of an ongoing series titled 'Getting to really know GWT'.
GWT 1.5 introduces JavaScript overlay types to make it easy to integrate entire families of JavaScript objects into your GWT project. There are many benefits of this technique, including the ability to use your Java IDE's code completion and refactoring capabilities even as you're working with untyped JavaScript objects.
The article shows how to create a Java bean-style wrapper for JSON data:
var jsonData = [
{ "FirstName" : "Jimmy", "LastName" : "Webber" },
{ "FirstName" : "Alan", "LastName" : "Dayal" },
{ "FirstName" : "Keanu", "LastName" : "Spoon" },
{ "FirstName" : "Emily", "LastName" : "Rudnick" }
];
The corresponding GWT Java object can combine JSNI method calls with regular Java methods to produce a safely-typed Java object with built-in utility:
class Customer extends JavaScriptObject {

// Overlay types always have protected, zero-arg ctors
protected Customer() { }

// Typically, methods on overlay types are JSNI
public final native String getFirstName() /*-{ return this.FirstName; }-*/;
public final native String getLastName() /*-{ return this.LastName; }-*/;

// Note, though, that methods aren't required to be JSNI
public final String getFullName() {
return getFirstName() + " " + getLastName();
}
}

class JsArray<E extends JavaScriptObject> extends JavaScriptObject {
protected JsArray() { }
public final native int length() /*-{ return this.length; }-*/;
public final native E get(int i) /*-{ return this[i]; }-*/;
}
The remaining step is to translate the Javascript objects into Java objects, which is done through variable inference and another JSNI call:
private final native JsArray<Customer> getCustomers() /*-{
return $wnd.jsonData;
}-*/;
For more information on the overlay functionality, as well as the optimizations made possible by the GWT compiler, be sure to check out the original article.

Hello stranger!

You need to Register an InfoQ account or to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread
Community comments

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Discuss

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2013 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT