gpt4 book ai didi

java - GWT.create(clazz) "generics"方法

转载 作者:行者123 更新时间:2023-11-30 09:05:41 25 4
gpt4 key购买 nike

我必须为 GWT/GXT 项目开发一个“通用”wigdet,为此我需要创建一个类型未知的对象实例。我找到了一种在开发模式下完美运行的方法,但是当我尝试编译我的项目并部署它时,我得到了一个 Only class literals may be used as arguments to GWT.create() 错误。

这是我所做的示例:

public class GenericEditableGrid<M> extends Grid<M>{
private final ToolBar toolBar = new ToolBar();
private final TextButton newItemButton = new TextButton();
protected GridInlineEditing<M> editing;
private final Class<M> clazzM;

public GenericEditableGrid(Class<M> parametrizedClass, String gridTitle, ListStore<M> listStore, ColumnModel<M> cm) {
super(listStore, cm);
clazzM = parametrizedClass;
// ... then I create my widget
bind();
}
private void bind(){
newItemButton.addSelectHandler(new SelectEvent.SelectHandler() {
@Override
public void onSelect(SelectEvent selectEvent) {
editing.cancelEditing();
// it is the folliwing line which is the problem obviously
M element = GWT.create(clazzM);
getStore().add(0, element);
int index = 0;
editing.startEditing(new Grid.GridCell(getStore().indexOf(element), index));
}

});
}
}

这就是我在子类中使用它的方式:

super(InternationalString.class, gridTitle, new ListStore<InternationalString>(isprops.key()), buildColumnModel());

基本上,我想知道这种方法到底有什么问题,最终我应该怎么做才能让它变得更好。

请注意,我关心的不仅仅是让它发挥作用,更重要的是如何以正确的方式做到这一点。因为我可以使用处理子类中的 GWT.create() 方法的抽象方法来避免这个问题。但这不是我想要的设计,它看起来不对。

我也不明白这样做有什么区别:

MyClass e = GWT.create(MyClass.class);

和:

Class<MyClass> clazz=MyClass.class;
MyClass e = GWT.create(clazz);

因为就我而言,我认为这基本上就是我正在做的事情,而且看起来是一回事。不是吗?

最佳答案

this forum 中有一个措辞良好的解释:

As the error message indicates, only class literals may be passed to the GWT.create method. The reason for this is that all GWT.create calls are basically turned into constructors at compile time, using the deferred binding rules for your module. As a result, all classes must be decided at compile time - your code requires that the at runtime the class is decided. This is too late, and so cannot be compiled.

GWT is not proper java, and so cannot be always treated as java. This is one such example of things that cannot be done in gwt. ...

What is it you are trying to do? Either you are making it far more complicated than it needs to be, or you need to write a generator to do it instead of taking this approach.

关于java - GWT.create(clazz) "generics"方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24789734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com