简体   繁体   English

在运行时识别类

[英]Identify classes at run-time

I'm working in a project for Android using libGDX framework in which I show some examples of the use of three graphic libraries. 我正在使用libGDX框架的Android项目中,展示一些使用三个图形库的示例。 Once started, the app must show a menu with a link for each sample, its title and a little description. 启动后,该应用程序必须显示一个菜单,其中包含每个样品的链接,其标题和简短说明。 For the time being, I'm creating all manually, declaring a new link for each sample, but as I will have a lot of samples and I'll add new ones in each app version, I would like to identify them and generate a new entry automatically. 目前,我正在手动创建所有示例,为每个示例声明一个新链接,但是由于我将有很多示例,并且我将在每个应用程序版本中添加新示例,因此我想识别它们并生成一个自动输入新条目。

The samples part is composed of an abstract class called Sample and a class for each sample that extends from Sample . 样本部分由一个称为Sample的抽象类和一个从Sample扩展的每个样本的类组成。 How could I accomplish this? 我该怎么做? The requisites will be to have the possibility to identify all samples at run-time and get information about them (name, description, etc.) without the need of create an instance previously. 前提是可以在运行时识别所有样本并获取有关样本的信息(名称,描述等),而无需事先创建实例。

My actual options are use Annotations (don't know if it is possible or if I need an external library to search for this annotations at run-time) or use something like a JSON file. 我的实际选择是使用Annotations(不知道是否可能,或者是否需要外部库在运行时搜索此注释)或使用类似JSON文件的方法。 What do you think is the best way (I'm open to other solutions of course) to solve this problem? 您认为解决此问题的最佳方法是什么(当然,我愿意接受其他解决方案)?

I would recomend using XML and take the class you want to create as Tag so something like this: 我建议使用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>

This can now be parsed with the XmlReader of libgdx to a Element . 现在,可以使用libgdx的XmlReader将其解析为Element So the element is not the root. 因此元素不是根。 Last but not least you can iterate over the childs of the root and check what the name of the Tag is. 最后但并非最不重要的一点是,您可以遍历root的子代并检查Tag的名称。 Depending on the name you create a different implementation of your Sample . 根据名称,您可以创建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