I have the following two classes:
public class User {
public Integer userId;
// ...another 50-60 fields
}
public class SuperUser extends User {
}
I would like to have a constructor in SuperUser which takes an object of type User and creates an object of type SuperUser. For example:
public SuperUser(User theUser) {
// not legal -> but I am looking for a one-liner to initialize this with values from theUser
this = theUser;
}
If the User object lacks the constructor User(User existingUser), is there any automatic way to initialize the SuperUser object with all of the fields from the existing user object? I’m trying to avoid 50 lines of:
public SuperUser(User theUser) {
this.firstName = theUser.getFirstName();
this.lastName = theUser.getLastName();
// and so on....
}
If this cannot be done, is there a refactoring like “Create Copy Constructor?”
Thanks!
Take a look at commons-beanutils‘s
BeanUtils.copyProperties(..):Alternatively you can place this in the copy-constructor: