0

我有一个泛型 CHILDITEMS 的 ObservableList,其中<CHILDITEMS extends PlanItem>. 我怎么知道 ObservableList 在运行时是什么类型?

    /*Get a reference to the child items of the currently viewed item.*/
    ObservableList<CHILDITEMS> childItems = (ObservableList<CHILDITEMS>) viewing.getChildItems();
    /*Set the child items label to the type of the child items.*/
    childItemsLabel.setText("Name of CHILDITEMS class");

我不能使用 getFields 因为 CHILDITEMS 并不是一个真正的字段。在 ObservableList.class 上使用 getType 只会返回泛型类型“E”,而不是在运行时返回的类型。

CHILDITEM 类型可以是 Goal、Objective、Strategy 或 Task。我想知道它在运行时是什么。

4

1 回答 1

0

正如@Romski 在评论中所说,这些信息甚至不会在运行时保留。

如果您知道您的列表是非空的,并且您只将确切类型的项目放入列表中(即您ObservableList<P>只包含运行时类型的P项目,而不是任何作为子类实例的项目P),那么您当然可以这样做list.get(0).getClass(),但这是不太可能发生的情况,而且不是很稳健。

您还可以考虑为列表创建一个包装器,使用类型标记来保留类型。就像是:

public class TypedObservableList<P extends PlanItem> {
    private final Class<P> type ;
    private final ObservableList<P> list ;

    public TypedObservableList(Class<P> type) {
        this.type = type ;
        this.list = FXCollections.observableArrayList();
    }

    public Class<P> getType() {
        return type ;
    }

    public ObservableList<P> getList() {
        return list ;
    }
}

现在你会得到很多看起来像的代码

TableView<Goal> goalTable = new TableView<>();
TypedObservableList<Goal> goals = new TypedObservableList<>(Goal.class);
goalTable.setItems(goals.getList());

但至少你现在可以做到

TypedObservableList<? extends PlanItem> typedList = viewing.getChildItems();
childItemsLabel.setText(typedList.getType().getSimpleName());

您还没有说是什么viewing,但是您也许可以提出一个类似的解决方案,其中该类包含类型令牌,因此您最终会得到

childItemsLabel.setText(viewing.getChildType().getSimpleName());
于 2014-09-02T01:05:03.113 回答