我在一个类中有一个字段,只能直接从getter访问.举个例子…
public class CustomerHelper {
private final Integer customerId;
private String customerName_ = null;
public CustomerHelper(Integer customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
if(customerName_ == null){
// Get data from database.
customerName_ = customerDatabase.readCustomerNameFromId(customerId);
// Maybe do some additional post-processing, like casting to all uppercase.
customerName_ = customerName_.toUpperCase();
}
return customerName_;
}
public String getFormattedCustomerInfo() {
return String.format("%s: %s", customerId, getCustomerName());
}
}
因此,即使在类本身内,诸如getFormattedCustomerInfo之类的函数也不能通过customerName_访问它.除了提供的getter函数之外,是否有一种方法可以强制类不直接访问字段?
解决方法:
似乎您正在尝试缓存数据库值,并希望防止访问尚未缓存的值.
如果是这样,则变量CustomerName_不应存在于CustomerHelper类中;缓存的值应该更靠近数据库存在.
方法customerDatabase.readCustomerNameFromId(customerId)应该首先查看缓存,如果缓存为空,则调用数据库并缓存结果.
实际上,customerName_成为高速缓存中的值:Map< Integer,String>缓存,其中键是customerId.