Java instanceof operator and class return method

I am writing my own implementation of TableModel . Since I will need several different implementations that share some functions, I decided to prepare an abstract class first. The fields of the table are:

 protected Object[][] lines; 

Basically, all the elements in one column should be of the same type, however, the classes of columns can vary in different implementations. I would like to write a generic setValueAt function in an abstract class, checking if val correct type or not.

 @Override public void setValueAt(Object val, int row, int col) { if (val instanceof this.getColumnClass(col)) lines[col][row] = val; } 

Compiler Error:

 Syntax error on token "instanceof", == expected 

Why?

+4
source share
2 answers

The correct instanceof operand must be a ReferenceType (JLS 15.20) . Use

 if (this.getColumnClass(col).isInstance(val)) 
+6
source

Instead of using instanceof you can use a generic type in your abstract class. You can declare this 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; } } 

That way you can let Java handle type checking for translation.

You can also just write one general class if the only difference between the classes is the type of values.

+2
source

Source: https://habr.com/ru/post/1480116/


All Articles