关于GWT.create结合UI-Binder声明接口并创建实例的疑问
Let’s break down exactly what’s happening here, and why that interface is critical to how GWT builds your UI:
First, a quick correction to your understanding
You mentioned GWT.create creates the interface instance at runtime—but actually, the heavy lifting happens at compile time. GWT’s compiler scans for interfaces that extend UiBinder, generates a concrete implementation class for it (you’ll never see this class in your source code), and GWT.create just instantiates that pre-generated class at runtime.
Why we need the TestEditorUiBind interface
This interface acts as a contract between your Java view class and GWT’s code generator, and serves three key purposes:
Defines binding constraints
By extendingUiBinder<Widget, TestEditorViewImpl>, you’re telling GWT two things:- The UI template (your
.ui.xmlfile) will produce aWidgetas its root element. - The template should be bound to an instance of
TestEditorViewImpl(thethisyou pass tocreateAndBindUi). This links the XML’s elements to your view class’s@UiFieldannotated fields and event handlers.
- The UI template (your
Triggers code generation
GWT’s compiler looks for all interfaces that inherit fromUiBinder. When it findsTestEditorUiBind, it locates the corresponding.ui.xmlfile (usually matching the interface or view class name by convention) and generates an implementation class. This generated class contains all the logic to:- Inflate the XML into actual GWT Widgets.
- Bind those widgets to your view class’s fields.
- Attach event handlers defined in the XML to your view’s methods.
Enforces type safety
The generic parameters inUiBinder<Widget, TestEditorViewImpl>let the compiler validate that your view class and XML template are compatible before you even run the app. For example, if you try to bind aButtonin XML to aLabelfield in your view, the compiler will throw an error—saving you from runtime bugs.
The full flow in action
Here’s how it all comes together:
- You write
TestEditorViewImplwith@UiFieldfields and event handler methods. - You define the
TestEditorUiBindinterface extendingUiBinder(the part you’re asking about). - You create a
.ui.xmlfile that describes your UI layout, referencing your view’s fields and handlers. - At compile time, GWT generates an implementation of
TestEditorUiBindthat handles all the XML inflation and binding logic. - At runtime,
GWT.create(TestEditorUiBind.class)instantiates that generated implementation, anduiBinder.createAndBindUi(this)runs the binding to build your fully functional UI.
In short, this interface isn’t just arbitrary—it’s the glue that connects your Java code to GWT’s UiBinder code generation system. Without it, GWT has no way to know how to map your XML template to your view class.
内容的提问来源于stack exchange,提问作者Jayesh Dhandha

