Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Instantiating an object from a class type

Tags:

java

I happened upon a seemingly simple problem that I have trouble figuring out. My goal is to create a spawner object that creates an object whenever it is called, something like this:

public class FishSpawner{
   public Fish spawnFish(){
      return new BlueFish(0, 0);
   }
}

This works and lets me create blue fish at the 0,0 coordinates of my world. But instead of copying this class for each type of Fish I want to spawn I figured i save the type of fish I want to spawn in the constructor and then create an object of that class in the spawn function. Like this:

public class FishSpawner{

private Class<? extends Fish> fishType;

public FishSpawner(Class<? extends Fish> fishType){
   this.fishType = fishType;
}

   public Fish spawnFish(){
      return fishType.newInstance(0, 0);
   }
}

However this does not work. It tells me that newInstance is deprecated and it also won't allow me to pass arguments to its constructor. But all the examples I've managed to google up use the newInstance method. Could anybody here point me in the right direction?

like image 230
Rob de Haan Avatar asked Dec 14 '25 14:12

Rob de Haan


1 Answers

You can achieve it by doing the following

public <T extends Fish> spawnFish(){
      Constructor<T> constructor = fishType.getConstructor(Integer.class, Integer.class);
      return constructor.newInstance(0, 0);
}

like image 132
h0ss Avatar answered Dec 16 '25 03:12

h0ss