Search code examples
javagame-development

How can I create another object of the same class which object I have in variable?


I'm creating a video game and I have this problem:

I have an ArrayList "inventory" that stores objects "Item". npc.inventory.get(index) this line returns an object from npc's inventory. I want to create new object of class which object is in this line. How can I do that? Is that possible?

Currently in every class I put the name of class in variable "name" and made ifs for every class like:

if (npc.inventory.get(index).name.equals("sword")) 
    Item newItem = new Sword();`

Can I fix my problem without creating if for every possible class?


Solution

  • You can do it by getting the class of the object and calling the default constructor. However, the result must be a generic Object, as you don't know the type of the class. That might be a problem for type save programming later on:

    try {
        Class<?> newItemClass = npc.inventory.get(index).getClass();
        Object newItem = newItemClass.getDeclaredConstructor().newInstance();
    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
        // Handle any exceptions
    }