Skip to content

GWT Mini Pattern: Bare Bones Entry Point Class

Don’t ever let your entry point class do anything. Why? Because the constructor of the entry point class will be called twice. Once when the object is being instantiated so that onModuleLoad can be called, and then once if your code does anything useful in the constructor. You can also have a constructor that does nothing active (XHR, modifying the DOM) in which case it won’t matter that it is called twice (except it will slow down the user’s computer a little bit.)
Here’s an example of how not to do it (sorry for the [lack of] code formatting):

 

public class Display implements EntryPoint {  public void onModuleLoad() {  final RootPanel rootPanel = RootPanel.get(COMPONENT_HOME_ID);  if (rootPanel != null) {  Display fd = new Display();  } }  public Display() { Window.alert("new date: "+new Date()); // more stuff }  // more stuff }

If you were to compile and execute the code above, you'd see two different alerts. Instead you want:

public class DisplayEntry implements EntryPoint {  public void onModuleLoad() {  final RootPanel rootPanel = RootPanel.get(COMPONENT_HOME_ID);  if (rootPanel != null) {  Display fd = new Display();  } }  }  class Display { // or it could be in a separate java file public Display() { Window.alert("new date: "+new Date()); // more stuff }  // more stuff }

You can also get around it by having a no-op no arg constructor (which all EntryPoint classes are required to have) and one that takes arguments that you'll use in your class to do something.

Tested on Windows, GWT 1.4.62.