簡體   English   中英

ObservableArrayList:如何通過反射獲取泛型類型?

[英]ObservableArrayList: How to get type of generic through reflection?

我有一個通用類型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類型可以是目標,目標,策略或任務。 我想知道在運行時是哪個。

正如@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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM