Q:

Calling a method and making object of an unknown class in Java

I have a problem with going back and adding to the main loop of my game, This task would be eliminated if I could create objects from classes I don't know about.
Right now I have:
if (Monesers.Zombie.canBeCreated(world,objects)){
    Zombie.add(new Monster())
}

if (Monesers.Sceleton.canBeCreated(world,objects)){
    objects.add(new Monster())
}

I am looking for something I can loop to all classes without mentioning the name the class so I don't have to copy the same code over and over for every new thing in the game.

A:

Reflection will get you somewhere... I don't know if it's the preferred method though.
You could do something like this. Have every monster type implement an interface, something like this:
public interface Monster {

    public boolean canBeCreated ( );

}

Then you could have a monster creator, something like this:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class MonsterCreator {

    private Monster[] monsterTypes;

    public MonsterCreator ( ) {
        monsterTypes = new Monster[2];
        monsterTypes[0] = new Zombie ( );
        monsterTypes[0] = new Skeleton ( );
    }

    public void tick ( ) {
        for ( Monster m : monsterTypes ) {
            if ( m.canBeCreated ( ) ) {
                try {
                    Constructor< ? >[] constr = m.getClass ( )
                        .getConstructors ( );
                    Monster toAdd = ( Monster ) constr[0].newInstance ( );
                    MonsterContainer.add ( toAdd );
                } catch ( InstantiationException | IllegalAccessException
                    | IllegalArgumentException | InvocationTargetException e ) {
                    e.printStackTrace ( );
                }
            }
        }
    }

}

It's worth a try... :)
Of course the thing with the monster types can be done neater with something like a map of enum constants linked to class types... Again, this is just for the sake of the example. Just wanted to get this posted before the question got closed!

