英文:
Java Instantiating an object from a class type
问题
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?
英文:
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?
答案1
得分: 3
你可以通过以下方式实现它:
public <T extends Fish> T spawnFish(){
Constructor<T> constructor = fishType.getConstructor(Integer.class, Integer.class);
return constructor.newInstance(0, 0);
}
英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论