这样的烂代码,我实习的时候都写不出来!
共 5626字,需浏览 12分钟
·
2021-07-31 18:41
//从数据库中查询出当前订单,并加锁
OrderDetail orderDetail = orderDetailDao.queryForLock();
//copy一个新的订单模型
OrderDetail newOrderDetail = new OrderDetail();
BeanUtils.copyProperties(orderDetail, newOrderDetail);
//对新的订单模型进行修改逻辑操作
newOrderDetail.update();
//使用修改前的订单模型和修改后的订单模型组装出订单变更流水
OrderDetailStream orderDetailStream = new OrderDetailStream();
orderDetailStream.create(orderDetail, newOrderDetail);
2、深拷贝:对基本数据类型进行值传递,对引用数据类型,创建一个新的对象,并复制其内容,此为深拷贝。
我们举个实际例子,来看下为啥我说BeanUtils.copyProperties的过程是浅拷贝。
public class Address {
private String province;
private String city;
private String area;
//省略构造函数和setter/getter
}
class User {
private String name;
private String password;
private Address address;
//省略构造函数和setter/getter
}
User user = new User("Hollis", "hollischuang");
user.setAddress(new Address("zhejiang", "hangzhou", "binjiang"));
User newUser = new User();
BeanUtils.copyProperties(user, newUser);
System.out.println(user.getAddress() == newUser.getAddress());
newUser.getAddress().setCity("shanghai");
System.out.println(JSON.toJSONString(user));
System.out.println(JSON.toJSONString(newUser));
{"address":{"area":"binjiang","city":"shanghai","province":"zhejiang"},"name":"Hollis","password":"hollischuang"}
{"address":{"area":"binjiang","city":"shanghai","province":"zhejiang"},"name":"Hollis","password":"hollischuang"}
public class Address implements Cloneable{
private String province;
private String city;
private String area;
//省略构造函数和setter/getter
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class User implements Cloneable{
private String name;
private String password;
private Address address;
//省略构造函数和setter/getter
@Override
protected Object clone() throws CloneNotSupportedException {
User user = (User)super.clone();
user.setAddress((Address)address.clone());
return user;
}
}
User newUser = JSON.parseObject(JSON.toJSONString(user), User.class);
class User implements Serializable
class Address implements Serializable
User newUser = (User) SerializationUtils.clone(user);
推荐阅读:
喜欢我可以给我设为星标哦