如何解决Java通用通配符限制 [英] How to work around Java generic wildcard limitations

查看:229
本文介绍了如何解决Java通用通配符限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试迭代JavaFX TableView 的列时遇到了这个问题。我想调用每个列的 cellFactory ,所以我做了类似的事情 -

I came across this problem while trying to iterate over columns of a JavaFX TableView. I want to call each column's cellFactory, so I did something like this -

for (TableColumn<Model, ?> column : getTableView().getColumns()) {
    column.getCellFactory().call(column);
}

不幸的是,这不起作用,因为我收到编译错误:

Unfortunately, this doesn't work, as I get a compilation error:


不兼容的类型:javafx.scene.control.TableColumn<模型,捕获#1? >无法转换为javafx.scene.control.TableColumn<模型,捕获#2? >

incompatible types: javafx.scene.control.TableColumn< Model,capture#1 of ? > cannot be converted to javafx.scene.control.TableColumn< Model,capture#2 of ? >

我如何克服这个问题?我可以投射参数吗?介绍显式类型参数?

How can I overcome this? Can I cast the parameter? Introduce explicit type-parameters?

这些列自然不是完全相同的类型,我非常希望避免对每列的类型进行硬编码,因为应该使用此代码各种 TableView s。

The columns are naturally not all the same type, and I would very much like to avoid having to hard-code the type of every column, as this code should be used for various TableViews.

推荐答案

您可以删除generics参数和抑制rawtypes警告

You can drop the generics parameter and suppress the rawtypes warning

for (@SuppressWarnings("rawtypes") TableColumn column : getTableView().getColumns()) {
    column.getCellFactory().call(column); // now compiles
}

这篇关于如何解决Java通用通配符限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆