What is the difference between GWT.create(SomeClass.class)
and new SomeClass()
?
Why would you use one over the other?
What is the difference between GWT.create(SomeClass.class)
and new SomeClass()
?
Why would you use one over the other?
GWT.create employs deferred binding work to around for the lack of reflection support.
According to the FAQ:
Deferred Binding is Google Web Toolkit's answer to Java reflection.
It's easiest to explain Deferred Binding by starting with a use case. Every web browser has its own idiosyncrasies, usually lots of them. (The sheer unmanageable number of them is the problem GWT was created to solve in the first place.) The standard Java way of dealing with idiosyncrasies would be to encapsulate the custom code into subclasses, with one subclass for each supported browser. At runtime, the application would use reflection and dynamic classloading to select the appropriate subclass for the current environment, load the class, create an instance, and then use that instance as the service provider for the duration of the program.
This is indeed what GWT does. However, the JavaScript environment in which GWT applications ultimately run simply does not support dynamic classloading (also known as dynamic binding.) You can certainly include code to support each browser in your generated JavaScript code, but to do so you must include support for all browsers is in the single application file. Why should an Opera user have to download code specific to Firefox, when there is no chance at all that she will ever need it?
Because dynamic binding is unavailable as a technique to GWT, GWT instead uses deferred binding. One way to think of this is as "dynamic class-loading that occurs at compile time instead of execution time." When the GWT Compiler compiles your Java application, it determines all the different "idiosyncrasies" that it must support, and generates a separate, tightly streamlined version of the application for that specific configuration. For example, it generates a different version of the application file for Firefox than it does for Opera.
GWT.create
is used by the GWT compiler for deferred binding. Deferred binding is a feature of the GWT compiler that works by generating many versions of code at compile time, only one of which needs to be loaded by a particular client during bootstrapping at runtime.
You should only use the GWT.create
for those cases that depend on this specific use case. For example when creating a RPC class: (MyServiceAsync)GWT.create(MyService.class)
. In all other cases use new
.
For more information check the GWT page on Deferred binding: http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsDeferred.html