简体   繁体   English

java instanceof运算符和类返回方法

[英]java instanceof operator and Class-returning method

I'm writing my own TableModel implementation. 我正在编写自己的TableModel实现。 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. 我想在抽象类中编写一个常见的setValueAt函数,检查val是否属于正确的类型。

@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) . instanceof的右操作数必须是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. 您可以考虑在抽象类中使用泛型类型,而不是使用instanceof 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. 这样,您可以让Java处理强制转换的类型检查。

You could also just write a single generic class, if the only difference between the classes is the type of the values. 如果类之间的唯一区别是值的类型,您也可以只编写一个泛型类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM