【问题标题】:Retrieve class type, and instantiate a new one of same type检索类类型,并实例化一个新的相同类型
【发布时间】:2018-04-28 16:15:40
【问题描述】:

我有一个类 Animals,它有两个子类 Cat 和 Dog。我想写一个复制方法。由于 Cats 和 Dogs 都可以繁殖,因此应该在 Animals 中使用这样的方法,显然猫应该只生成猫等。所以在超类 Animals 中我有这样的东西:

public void Reproduce(){
   addAnimal(new Type);
}

其中 Type 表示我们想要创建另一个类(猫或狗)。当然,我想编写代码以便以后可以添加其他类别的动物,例如马之类的。所以我想要的是这样的:

public void Reproduce(){
   addAnimal(new this);
}

这样 cat.Reproduce() 会启动 Cat 类的新实例,而 dog.Reproduce() 会实例化新的 Dog,等等。

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

编辑:为了更清楚,我找到了几种不同的方法来找出当前类,例如 this.getClass();。但是,我还没有找到一种方法来使用该信息来创建相同类型的新类。做这样的事情:

Class c = this.getClass();
Animals offspring = new c; 

不起作用。

【问题讨论】:

    标签: java class


    【解决方案1】:

    有两种选择。首先是让你的类实现像这样的Cloneable接口

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      • 2015-09-07
      相关资源
      最近更新 更多