我有此类公共类IndexedColumn扩展了Column< List< String> ;, String>.我希望该类根据不同的键变量来替换不同的对象.
可以使用以下代码,但只有1个超级代码(新的ClickableTextCell())
public class IndexedColumn extends Column, String>{
private final int index;
public IndexedColumn(int index) {
super(new ClickableTextCell());
this.index = index;
}
@Override
public String getValue(List object) {
return object.get(this.index);
}
public int getIndex(){
return index;
}
}
在其他班级
int myIndx=getIndex();
IndexedColumn nameColumn=null;
if(text.equals("clickText")){
nameColumn=new IndexedColumn(myIndx);
}
但是,如果我想同时超级(new ClickableTextCell())和super(new ButtonCell()),然后出现错误
public class IndexedColumn extends Column, String>{
private final int index;
public IndexedColumn(int index, int cellType) {
if(cellType==1)
super(new ClickableTextCell());
else{
super(new ButtonCell());
}
this.index = index;
}
}
因此,日食建议我使用另一个这样的构造函数:
public class IndexedColumn extends Column, String>{
private final int index;
public IndexedColumn(int index) {
super(new ClickableTextCell());
this.index = index;
}
public IndexedColumn(int index, int forNothingKey) {
super(new ButtonCell());
this.index = index;
}
}
然后在其他班级
int myIndx=getIndex();
IndexedColumn nameColumn=null;
if(text.equals("clickText")){
nameColumn=new IndexedColumn(myIndx);
}
else if(text.equals("clickButton")){
int forNoGoodReason=1;
nameColumn=new IndexedColumn(myIndx, forNoGoodReason);
}
如您所见,为了能够使用ButtonCell列,我必须不使用int forNoGoodReason变量.
这样做是一种好习惯吗?
还是可以找到一种更好的方法来修复它?
解决方法:
在Java中,类的超类在类头中显式声明.例如
public class Foo extends Bar ... {
....
}
除Object以外的每个类都在编译时确定了一个超类.无法在运行时动态更改或选择它.
基于Java和Java类型系统的GWT具有相同的限制.
另一方面,您可以使用以下多个构造函数声明一个类:
public class Bar ... {
public Bar (Integer i) { ... }
public Bar (Double d) { ... }
}
并执行以下操作:
public class Foo extends Bar ... {
public Foo (Integer i) {
super(i);
...
}
public Foo (Double d) {
super(d);
...
}
}
但是,您无法执行以下操作:
public class Foo extends Bar ... {
public Foo (Integer i, Double d, boolean b) {
super(b ? i : d);
...
}
}
问题在于,构造函数中的超级调用必须基于提供给超级调用的参数的静态类型,在编译时解决超类中的单个构造函数重载.
如果要使用new来创建对象,获得这样的东西的唯一方法是在超类中有一个统一的构造函数来处理这两种情况.例如
public class Bar ... {
public Bar (Object o) {
if (o instanceof Integer) {
...
} else if (o instanceof Double) {
...
} // etcetera
}
}
…但这非常丑陋,更不用说它的脆弱性和有害的耦合了.
另一种选择是使用工厂方法…如下:
public class Foo extends Bar ... {
public Foo (Integer i) {
super(i);
...
}
public Foo (Double d) {
super(d);
...
}
public static Foo createFoo(Integer i, Double d, boolean b) {
return b ? new Foo(i) : new Foo(d);
}
}
标签:java,gwt
来源: https://codeday.me/bug/20191121/2055743.html