簡體   English   中英

在運行時識別類

[英]Identify classes at run-time

我正在使用libGDX框架的Android項目中,展示一些使用三個圖形庫的示例。 啟動后,該應用程序必須顯示一個菜單,其中包含每個樣品的鏈接,其標題和簡短說明。 目前,我正在手動創建所有示例,為每個示例聲明一個新鏈接,但是由於我將有很多示例,並且我將在每個應用程序版本中添加新示例,因此我想識別它們並生成一個自動輸入新條目。

樣本部分由一個稱為Sample的抽象類和一個從Sample擴展的每個樣本的類組成。 我該怎么做? 前提是可以在運行時識別所有樣本並獲取有關樣本的信息(名稱,描述等),而無需事先創建實例。

我的實際選擇是使用Annotations(不知道是否可能,或者是否需要外部庫在運行時搜索此注釋)或使用類似JSON文件的方法。 您認為解決此問題的最佳方法是什么(當然,我願意接受其他解決方案)?

我建議使用XML,並將要創建的類作為Tag,如下所示:

<root>
     <sampleimplement1 name ="sampleimplement1" descript="sample1 description" ..... more attributes here... />
     <sampleimplement2 name ="sampleimplement2" descript="sample2 description" ..... more attributes here... />
     <sampleimplement3 name ="sampleimplement3" descript="sample3 description" ..... more attributes here... />
</root>

現在,可以使用libgdx的XmlReader將其解析為Element 因此元素不是根。 最后但並非最不重要的一點是,您可以遍歷root的子代並檢查Tag的名稱。 根據名稱,您可以創建Sample的不同實現。

XmlReader r = new XmlReader();
Element e = r.parse(xml);//<--- the XML as string also possible as file
for (int i = 0; i < e.getChildCount(); i++)
    {
        Element child = e.getChild(i);
        switch(child.getName()){
            case "sampleimplement1":
            //create sample1
            break;
....
....
    }

暫無
暫無

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

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