I have an abstract class:
public abstract class Room {
}
and inherited classes that are not known at compile time like:
public class MagicRoom extends Room {
public MagicRoom(){
System.out.println("Creating a MagicRoom.");
}
public String magic = "";
}
or:
public class Dungeon extends Room {
public Dungeon(){
System.out.println("Creating a Dungeon");
}
public String keeper = "";
}
I have a class that I will be creating instances of these classes from:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class MazeGame {
public static Room makeRoom(Class roomClass)
throws IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException,
SecurityException, NoSuchMethodException{
Constructor c = roomClass.getConstructor();
return c.newInstance();
}
}
makeRoom is my attempt to create a class inherited from Room which type I don't know at compile time, but I'm not sure what to put as its return type instead of Room. Because makeRoom returns a Room I get an exception if I try to use a field that belongs to an inherited class:
import java.lang.reflect.InvocationTargetException;
public class FactoryTest {
public static void main(String[] args)
throws IllegalArgumentException, SecurityException,
InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException{
MazeGame game = new MazeGame();
Room magicRoom = MazeGame.makeRoom(MagicRoom.class);
magicRoom.magic = "a";
}
}
Thanks in advance.