Home > Software engineering >  How can I recreate an object in java?
How can I recreate an object in java?

Time:04-02

How can I recreate an object?

candies.add(new MilkCandy());
candies.add(new StrawberryCandy());
candies.add(new WaterMelonCandy());

How can I recreate an new candy based on it?

I can use that:

for (Candy c: candies){
    if (c.getClass.getSimpleName == "StrawberryCandy"){
        return new MilkCandy();
    if (c.getClass.getSimpleName == "WaterMelonCandy"){
        return new WaterMelonCandy();
    ...

But it will took so long, and so too complicated I tried this, but not work

return new (c.getClass.getConstructor());

But it does't work

Are there any better way to do that?

CodePudding user response:

The correct way to create a an object instance of the same class as an existing object instance, provided that the class has a no arguments constructor, is

Object newObj = obj.getClass().getConstructor().newInstance();

CodePudding user response:

Not sure what you are after, but if you want to return a single Candy but dont know what class the candy will be, why not simply let the specific canty types extend a genereic Candy class and you can simply return a class that extends Candy?

You might also find this useful: https://www.baeldung.com/java-instanceof

  • Related