我有以下两节课:
public class User {
public Integer userId;
// ...another 50-60 fields
}
public class SuperUser extends User {
}
我想在SuperUser中有一个构造函数,该构造函数接受User类型的对象并创建SuperUser类型的对象。例如:
public SuperUser(User theUser) {
// not legal -> but I am looking for a one-liner to initialize this with values from theUser
this = theUser;
}
如果User对象缺少构造函数User(User existingUser),是否有任何自动方法可以使用现有用户对象中的所有字段初始化SuperUser对象?我正在尝试避免以下50行:
public SuperUser(User theUser) {
this.firstName = theUser.getFirstName();
this.lastName = theUser.getLastName();
// and so on....
}
如果无法做到这一点,是否存在像“创建副本构造函数”这样的重构?
谢谢!
看一下commons-beanutils的BeanUtils.copyProperties(..)
:
SuperUser superUser = new SuperUser();
BeanUtils.copyProperties(superUser, originalUser);
或者,您可以将其放置在复制构造函数中:
public SuperUser(User originalUser) {
BeanUtils.copyProperties(this, originalUser);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句