Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I recreate an object in java?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading