Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an abstract class:

Java
public abstract class Room {

}


and inherited classes that are not known at compile time like:

Java
public class MagicRoom extends Room {
	
	public MagicRoom(){
		System.out.println("Creating a MagicRoom.");
	}
	
	public String magic = "";
}


or:

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

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


Java
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);
		
		/*
		 * Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
		 * magic cannot be resolved or is not a field
		 */
		
		magicRoom.magic = "a"; 

	}
}


Thanks in advance.
Posted
Comments
Rob Philpott 6-Feb-14 13:16pm    
Use .NET?
[no name] 6-Feb-14 13:19pm    
I wish I could.
Rob Philpott 6-Feb-14 13:21pm    
I feel your pain.

1 solution

I needed to make the method generic, got the answer on StackOverflow here:

the solution[^]

For reference, here is the code:

Java
public static  T makeRoom(Class roomClass) 
    throws IllegalArgumentException, InstantiationException, 
        IllegalAccessException, InvocationTargetException, 
        SecurityException, NoSuchMethodException{

    // This is enough, if you have 0-arg constructor in all your subclasses
    return roomClass.newInstance();
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900