Java 检索类类型,并实例化相同类型的新类

Java 检索类类型,并实例化相同类型的新类,java,class,Java,Class,我有一个动物类,它有两个子类猫和狗。我想写一个复制方法。因为猫和狗都会繁殖,所以这种方法应该应用于动物身上,很明显,猫应该只产猫,等等。所以在超级动物身上,我有这样的东西: public void Reproduce(){ addAnimal(new Type); } Class c = this.getClass(); Animals offspring = new c; 其中,Type表示我们想要创建另一个类的类,所以是cat还是dog。当然,我想编写代码,以便以后可以添加其他类

我有一个动物类,它有两个子类猫和狗。我想写一个复制方法。因为猫和狗都会繁殖,所以这种方法应该应用于动物身上,很明显,猫应该只产猫,等等。所以在超级动物身上,我有这样的东西:

public void Reproduce(){
   addAnimal(new Type);
}
Class c = this.getClass();
Animals offspring = new c; 
其中,Type表示我们想要创建另一个类的类,所以是cat还是dog。当然,我想编写代码,以便以后可以添加其他类的动物,如马或其他东西。所以我想要的是这样的:

public void Reproduce(){
   addAnimal(new this);
}
所以cat.repearchave将启动一个新的类cat实例,而dog.repearchave将实例化一个新的dog,等等

有办法做到这一点吗?或者该方法是否有办法检索调用它的实例的类类型,然后实例化一个新的类类型

编辑:为了让它更清楚,我找到了几种不同的方法来查找当前类,比如这个.getClass;。但是,我还没有找到一种方法来使用这些信息创建相同类型的新类。这样做:

public void Reproduce(){
   addAnimal(new Type);
}
Class c = this.getClass();
Animals offspring = new c; 

不起作用

有两种选择。首先是使类实现如下可克隆接口

class Cat implements Cloneable {
  // all your properties and methods

  @Override
  public Cat clone() throws CloneNotSupportedException {
        return (Cat)super.clone(); // if you need deep copy you might write your custom code here
  }

  public void Reproduce(){
    Cat c = this.clone();
    // change some properties of object c if needed
    addAnimal(c);
  }
}
第二种选择是使用反射,您可能需要在反射的使用周围添加try{}catch块

public void Reproduce() {
   Constructor c = tc.getClass().getDeclaredConstructor(String.calss, Integer.class); //pass types of parameters as in consrtuctor you want to use. In 
            //this case I assume that Cat class has constructor with first parameter of type String and second parameter of type Integer
   Cat cat = (Cat)c.newInstance("someString", 2); 
   // change some properties of object c if needed
   addAnimal(cat);
}