简体   繁体   English

Java 从 class 类型实例化 object

[英]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:我的目标是创建一个生成器 object,它在被调用时创建一个 object,如下所示:

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.这很有效,让我可以在我的世界的 0,0 坐标处创建蓝鱼。 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. 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.它告诉我 newInstance 已被弃用,它也不允许我将 arguments 传递给它的构造函数。 But all the examples I've managed to google up use the newInstance method.但是我设法用谷歌搜索的所有示例都使用了 newInstance 方法。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM