【问题标题】:Java create new instance of class based on another class [duplicate]Java基于另一个类创建类的新实例[重复]
【发布时间】:2021-06-02 20:31:07
【问题描述】:

假设我有 2 个对象数组,它们都扩展了同一个抽象类,我希望第二个列表的第一个元素是第一个数组中的第一个元素是同一类的新实例(假设它们采用相同的参数)。

Animals[] animals1 = new Animals[] {new Cat(), new Dog()...}

Animals[] animals2 = new Animals[] {new animals1[0].getClass()} //doesn't work obviously

有没有办法做到这一点?

【问题讨论】:

标签: java class object


【解决方案1】:

你可以这样做:

Animal.java

public interface Animal {
}

Cat.java:

public class Cat implements Animal {
}

狗.java:

public class Dog implements Animal {
}

进行映射的代码:

Animal[] animals1 = new Animal[] {new Cat(), new Dog()};
Animal[] animals2 = Arrays.stream(animals1).map(a -> {
    Animal animal = null;
    try {
        animal = a.getClass().getDeclaredConstructor().newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return animal;
}).toArray(Animal[]::new);

【讨论】:

    【解决方案2】:

    我会在抽象基类中创建一个抽象方法newInstance(),并让子类创建并返回自己的类型。例如,

    public abstract class Animal {
       // ... other methods
       public abstract Animal newInstance(/* parameters */);
    }
    
    public class Dog extends Animal {
        // ... other methods, fields
        @Override
        public Animal newInstance(/* parameters */) {
            Dog d = new Dog(/* ... */);
            // ...
            return d;
        }
    }
    // do this for other animals, they should instantiate and return their class
    

    对于列表:

    Animals[] animals2 = new Animals[] {animals[0].newInstance(/* ... */), ...};
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      相关资源
      最近更新 更多