我可以同时使用默认构造函数和@UiConstructor吗?

时间:2015-08-24 12:19:09

标签: java gwt uibinder

如果我使用两个构造函数创建一个GWT小部件:一个默认构造函数和另一个使用@UiConstructor注释的构造函数 - 是否可以在ui.xml模板中使用它们?或者@UiConstructor注释的存在是否意味着绝对没有办法使用任何其他构造函数?

2 个答案:

答案 0 :(得分:3)

结果答案是否:如果任何构造函数都标有@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模板中使用其中任何一个(除了带注释的模板)。默认构造函数不是此规则的例外。

我想如果可以使用带注释的和默认的构造函数,那么会导致混乱的情况。例如,如果我们有一个带有默认构造函数的小部件,一个带有String文本参数的UiConstructor,以及一个setText(String text)setter,那么这个模板声明将是不可能的:

<my:UiConstructorTest ui:field='testLabel' text="isThisAConstructorParameterOrASetterParameter?">

UiBinder是否应该使用UiConstructor标记构造函数进行实例化?或者它应该使用默认构造函数,然后调用setter?

答案 1 :(得分:1)

@UiConstructor的规范(可以找到here)说明了这一点 [@UiConstructor] Marks a constructor that may be used as an alternative to a widget's zero args construtor in a UiBinder template. The parameter names of the constructor may be filled as xml element attribute values.

因此,根据规范,您可以使用零参数构造函数和/或带注释的构造函数,其参数可以通过xml指定。除此之外,您不能拥有多个带注释的构造函数,因为在这种情况下UiBinder应该选择正确的构造函数。对于任何其他构造函数,我认为它将被忽略。

相关问题