I'm writing my own TableModel
implementation. As I shall need a few various implementations sharing some functionality, I decided to prepare an abstract class first. The fields of the table are represented by:
protected Object[][] lines;
Basically all elements in the same column should be of the same type, however column classes may vary among different implementations. I would like to write a common setValueAt
function in the abstract class, checking whether val
is of proper type or not.
@Override
public void setValueAt(Object val, int row, int col) {
if (val instanceof this.getColumnClass(col))
lines[col][row] = val;
}
The compiler signals error here:
Syntax error on token "instanceof", == expected
Why?
The right operand of instanceof
must be a ReferenceType
(JLS 15.20) . Use
if (this.getColumnClass(col).isInstance(val))
Rather than using instanceof
, you might consider using a generic type in your abstract class. You could declare it with something like:
protected abstract class MyTableModel<T> implements TableModel {
//...
protected T[][] lines;
//...
@Override
public void setValueAt(Object val, int row, int col) {
lines[col][row] = (T) val;
}
}
This way, you can let Java handle the type checking for the cast.
You could also just write a single generic class, if the only difference between the classes is the type of the values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.