我想替换对象的对象中的某个字段。
我需要替换的值在凭证对象中,它位于
CarBookingRequest> CarSegment>RentalPayentPref> Voucher>类型
现在,这是我的代码
//generate new voucher type for SV
String currencyCode = originalRequest.getCarSegment().getCarTotalPrice().getCurrencyCode();
String amount = originalRequest.getCarSegment().getCarTotalPrice().getAmount();
String carTotalPrice = currencyCode + amount;
//get Old Voucher values and re-assign type to carTotalPrice
Voucher voucher = new Voucher();
voucher.setBillingNumber(originalRequest.getCarSegment().getRentalPaymentPref().getVoucher().getBillingNumber());
voucher.setFormat(originalRequest.getCarSegment().getRentalPaymentPref().getVoucher().getFormat());
voucher.setType(carTotalPrice);
RentalPaymentPref rentalPaymentPref = new RentalPaymentPref();
rentalPaymentPref.setVoucher(voucher);
CarSegment carSegment = new CarSegment();
carSegment.setRentalPaymentPref(rentalPaymentPref);
originalRequest.setCarSegment(carSegment);
如何在不删除所有这些其他对象的现有值的情况下做到这一点,毕竟,凭证上面的这些对象有自己的值,我不需要更改,但需要保留。因为这个值已经被赋给了另一个代码中引用的变量。这个类在下面的代码中被引用。
CarBookingRequest newRequesst = originalRequestBody;
我尝试手动实例化所有高级类,只覆盖我需要的值,但它也从其他不需要更改的参数中删除了现有值。
下面是我的示例模型类:
CarbookingRequest.class
public class CarBookingRequest {
private CarSegment carSegment;
private List<Remark> remarks;
private String test;
}
CarSegment.class
public class CarSegment {
private String billingNumber;
private RentalPayentPref rental;
private String test;
}
RentalPayentPref.class
public class RentalPayentPref {
private Voucher Voucher;
private String test;
}
Voucher.class
public class Voucher {
private String amount;
private String type;
}
当你可以从getter方法中获得现有对象时,为什么要创建新对象?您只在答案中提供了getter方法,而在问题中没有。您可以这样使用它们:
originalRequest
.getCarSegment()
.getRentalPaymentPref()
.getVoucher()
.setType(newValue);
我刚刚意识到我可以用这一行代码做到这一点。
Optional.ofNullable(originalRequest)
.map(CarBookingRequest::getCarSegment)
.map(CarSegment::getRentalPaymentPref)
.map(RentalPaymentPref::getVoucher)
.ifPresent(voucher -> voucher.setType(carTotalPrice));
我的问题已经解决了。虽然我在上面标记的另一个答案可能是更好和更短的版本,因为已经不需要地图了,现有的值仍然保留。