Java 从类类型实例化对象

huangapple go评论78阅读模式
英文:

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&lt;? extends Fish&gt; fishType;

public FishSpawner(Class&lt;? extends Fish&gt; 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 &lt;T extends Fish&gt; spawnFish(){
      Constructor&lt;T&gt; constructor = fishType.getConstructor(Integer.class, Integer.class);
      return constructor.newInstance(0, 0);
}

huangapple
  • 本文由 发表于 2020年8月6日 01:27:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63270477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定