【发布时间】:2018-10-13 04:33:59
【问题描述】:
我在一个类中有一个只能直接从 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 函数之外,有没有办法强制类不直接访问字段?
【问题讨论】:
-
即使是私有类成员也可以在一个类中访问,所以我看不到这样做的直接方法。也许您可以将
getFormattedCustomerInfo移动到单独的 util 类。为什么需要这个? -
没有。一个类总是可以访问它的所有属性。唯一的可能是设置类抽象并编写一个具体类,由于属性设置为
private,因此必须使用getter。两点说明: - 在 Java 中,在属性末尾写下划线是不常见的 -Formattableinterface 是在类中添加所需功能的正确方法。 -
我不明白您为什么要这样做,但一种骇人听闻的方法是将字段提升到超类型并通过
protected或publicgetter 公开它。除此之外,我认为这是不可能的。
标签: java private encapsulation getter