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?
>Solution :
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();