我有一个扩展DataRow
的课程:
import org.jdesktop.dataset.DataRow;
public class MainDataRow extends DataRow {
private MainDataTable baseDataTable;
protected MainDataRow(MainDataTable dt) {
super(dt);
this.baseDataTable = dt;
}
public int getId() { return (int) super.getValue(baseDataTable.getColId()); };
public void setId(int id) { super.setValue(baseDataTable.getColId(), id); };
public int getDelta() { return (int) super.getValue(baseDataTable.getColDelta()); };
public void setDelta(int delta) { super.setValue(baseDataTable.getColDelta(), delta); };
public String getNombre() { return (String) super.getValue(baseDataTable.getColNombre()); };
public void setNombre(String nombre) { super.setValue(baseDataTable.getColNombre(), nombre); };
同样MainDataTable
扩展DataTable
,并返回getColId()
,getColDelta()
,getColNombre()
的有效列。
我想这样做:
MainDataTable dt = new MainDataTable(ds);
MainDataRow dr = (MainDataRow) dt.appendRow();
但由于CastClassException
(dt.appendRow
返回DataRow
而MainDataRow
正在延伸DataRow
,而不是相反,所以这是不可能的,所以唯一的可能性可能类似于DataRow dr = (DataRow) new MainDataRow(dt);
)。
在c ++中,可以通过DataRowBuilder
轻松实现,覆盖NewRowFromBuilder()
中的MainDataTable
并覆盖DataRowBuilder
中MainDataRow
的受保护创建者({{3} }})。
我怎么能用Java做到这一点?
修改
MainDataTable类:
public class MainDataTable extends TypedDataTable<MainDataRow> {
...
}
和TypedDataTable类:
public abstract class TypedDataTable<TypeOfRow> extends DataTable {
protected boolean locked;
public TypedDataTable(DataSet ds, boolean appendRowSupported) {
super(ds);
InitClass();
super.setAppendRowSupported(appendRowSupported);
locked = false;
}
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
@Override
public abstract DataRow appendRow();
@Override
public abstract DataRow appendRowNoEvent();
public abstract void InitVars();
public abstract void InitClass();
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
}
答案 0 :(得分:1)
覆盖MainDataTable中的appendRow()
和appendRowNoEvent()
以返回MainDataRow
public abstract class TypedDataTable<TypeOfRow extends DataRow> extends DataTable {
protected boolean locked;
public TypedDataTable(DataSet ds, boolean appendRowSupported) {
super(ds);
InitClass();
super.setAppendRowSupported(appendRowSupported);
locked = false;
}
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
@Override
public TypeOfRow appendRowNoEvent() {
if (appendRowSupported) {
TypeOfRow row = createDataRow(); //<-- HERE we create a MainDataRow!!!
rows.add(row);
return row;
} else {
return null;
}
}
@Override
public TypeOfRow appendRow() {
return (TypeOfRow)super.appendRow();
}
public abstract TypeOfRow createDataRow();
public abstract void InitVars();
public abstract void InitClass();
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
}