如果我创建一个带有两个构造函数的 GWT 小部件:一个默认构造函数和另一个用 @UiConstructor 注释的构造函数 - 是否可以在 ui.xml 模板中同时使用这两个构造函数?或者 @UiConstructor 注释的存在是否意味着绝对无法使用任何其他构造函数?
最佳答案
事实证明答案是否定的:如果任何构造函数都用 @UiConstructor 标记,那么您必须完全根据该单个构造函数编写 ui.xml 模板。测试小部件类:
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.ui.Label;
public class UiConstructorTest extends Label {
public UiConstructorTest() {
setText("default constructor");
}
@UiConstructor
public UiConstructorTest(String text) {
setText(text);
}
}
省略参数会导致如下的 UiBinder 错误(而不是调用默认构造函数):
00:00:15,072 [ERROR] <my:UiConstructorTest ui:field='testLabel'> missing required attribute(s): text: <my:UiConstructorTest ui:field='testLabel'> (:14)
当然,小部件仍然可以有其他构造函数。这一限制仅意味着您将无法在 ui.xml 模板中使用其中任何一个(带注释的模板除外)。默认构造函数也不异常(exception)。
我想如果可以同时使用带注释的构造函数和默认的构造函数,将会导致困惑的情况。例如,如果我们有一个带有默认构造函数的小部件、带有字符串文本参数的 UiConstructor 和 setText(String text) setter,则此模板声明将是不明确的:
<my:UiConstructorTest ui:field='testLabel' text="isThisAConstructorParameterOrASetterParameter?">
UiBinder 应该使用 UiConstructor 标记的构造函数进行实例化吗?或者应该使用默认构造函数,然后调用 setter?
关于java - 我可以同时使用默认构造函数和@UiConstructor吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32182166/