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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With