简体   繁体   中英

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. 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 . 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. 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:

<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 . 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. Depending on the name you create a different implementation of your 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;
....
....
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM