Solved Dynamic way to loop through objects.

Discussion in 'Plugin Development' started by Unica, May 7, 2015.

Thread Status:
Not open for further replies.
  1. Offline

    Unica

    Hello all,

    I'll be short and direct, I want to make a dynamic system for adding Items to my plugin, and
    I want to retrieve them by id, but i'm kind of stuck about the correct way.

    Example
    Imagine I have this 'Main abstract class', called Items
    Code:
    public abstract class Items{
       //Stuff here
    }
    Allright, so, imagine I would add three item classes.
    Code:
    public class Banana extends Items{}
    public class Apple extends Items{}
    public class Potato extends Items{}
    Now, somewhere in the code, I want to get an instance of the super class by a given id.
    Code:
    public Items getById(int id){
    }
    Problem
    If I would want to do this, I would make a that method in some kind of Manager, and manually add an integer there, and return the instance/object there.

    Like for example:
    Code:
    public Items getById(int id){
       switch(id){
       case 0: return new Potato();
       case 1: return new Apple();
       case 2: return new Banana();
       }
    }
    I would like this to go in a dynamic way, for when I create a new Items object/instance, that it automatically would be added to this 'switch' (or a list for that matter). I looked into reflection and looping through packages etc, but i'm extremely unfamiliar with that.

    Is there a way for this?

    Kind regards,

    Unica.

    Nvm, going for enums.

    Solved.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 12, 2016
Thread Status:
Not open for further replies.

Share This Page