0

Suppose, I have a class like this...

public class MyClass {
    private String firstName;
    private String lastName;

    public String getFirstName() // .... 
    // ... usual getters 
}

And I want to dynamically make a new object and has the exact same fields and values and add just three more? How do I do that. One idea convert MyClass to a Map and just add the fields.

Any better idea?

Thanks

More Than Five
  • 9,959
  • 21
  • 77
  • 127
  • 2
    What do you mean by _dynamically_? – Sotirios Delimanolis Mar 06 '23 at 20:46
  • 1
    There's aren't many "good" ways to do this in Java. You can create a "copy constructor" that takes an object of `MyClass` and copies all of its fields. You can use reflection to copy all fields. You can use `clone()`, but that is deprecated. You can serialize and deserialize objects, but that exposes a `Serializable` interface. – markspace Mar 06 '23 at 20:48
  • 1
    I wouldn't try to create a class dynamically. Because Java is a statically typed language, you would only be able to access it as an `Object`, and you would need to use reflection to access the values. Have you considered simply creating a Map? Since this is just a POJO and there's no behavior, this is the approach I would take. – lane.maxwell Mar 06 '23 at 21:51
  • 1
    See if [this](https://stackoverflow.com/questions/12832554/how-to-add-attributes-dynamically-for-java-object) helps? – Enowneb Mar 07 '23 at 04:17
  • https://stackoverflow.com/questions/869033/how-do-i-copy-an-object-in-java – Prashant Pandey Mar 08 '23 at 20:12

0 Answers0