
在java编程中,管理对象状态的完整性和隔离性至关重要。当一个类(如order)持有另一个可变类(如date)的实例作为其内部状态时,如果处理不当,外部代码可能会通过获取内部对象的引用并对其进行修改,从而意外地改变持有类的内部状态。这种现象常被称为“隐私泄露”或“状态泄露”。本文将通过一个具体的date和order类示例,详细阐述这种问题的原因,并提供两种业界推荐的解决方案:防御性拷贝和创建不可变对象,同时探讨构造器中参数验证的最佳实践。
Java采用的是“值传递”机制,但对于对象类型,传递的是对象引用的值。这意味着当一个对象(例如Date实例)被传递给另一个对象(例如Order的构造器)时,Order内部接收到的只是指向Date对象的引用副本,而不是Date对象本身的副本。如果Order类直接将这个引用赋值给其内部字段,那么Order内部和外部代码将共享同一个Date对象的引用。
问题示例:
考虑以下Date类和Order类片段:
public class Date {
private int month, day, year;
public Date(int month, int day, int year) {
// ... 参数验证,此处省略 ...
this.month = month;
this.day = day;
this.year = year;
}
public void setDay(int day) {
// 原始代码逻辑有误,应为 &&
if (day >= 1 && day <= 31) {
this.day = day;
} else {
// 更好的错误处理方式,将在后续讨论
System.out.println("Invalid day: " + day);
System.exit(0);
}
}
public int getDay() { return day; }
public int getMonth() { return month; }
public int getYear() { return year; }
// ... 其他方法 ...
}
public class Order {
private Date orderDate;
// ... 其他字段 ...
public Order(Money amount, Date date, String company, String product) {
this.orderDate = date; // 直接赋值,可能导致隐私泄露
// ... 初始化其他字段 ...
}
public Date getOrderDate() {
return orderDate; // 直接返回内部对象的引用,可能导致隐私泄露
}
// ... 其他方法 ...
}当执行以下JUnit测试时:
立即学习“Java免费学习笔记(深入)”;
@Test
public void OrderDatePrivacyLeaks() {
Date d = new Date(6, 12, 2017);
Order b = new Order(new Money(2, 33), d, "ACME Company", "widget");
d.setDay(10); // 外部修改了Date对象
Date billDate = b.getOrderDate(); // 获取Order内部的Date对象引用
assertEquals(12, billDate.getDay()); // 预期是12,但实际会得到10
}d.setDay(10)修改了外部Date对象的状态,由于Order内部的orderDate字段直接引用了同一个Date对象,Order的内部状态也随之改变。这违反了封装原则,导致了隐私泄露。
防御性拷贝的核心思想是在对象边界(如构造器参数和getter方法返回值)创建可变对象的独立副本,以确保内部状态不被外部代码意外修改。
实现步骤:
这要求被拷贝的类(如Date)提供一个合适的拷贝机制,例如拷贝构造器或clone()方法。
示例代码:
首先,为Date类添加一个拷贝构造器,并修正setDay的逻辑:
public class Date {
private int month, day, year;
// 原始构造器
public Date(int month, int day, int year) {
validateDate(month, day, year); // 提取验证逻辑
this.month = month;
this.day = day;
this.year = year;
}
// 拷贝构造器:用于创建现有Date对象的副本
public Date(Date otherDate) {
this(otherDate.getMonth(), otherDate.getDay(), otherDate.getYear());
}
// 参数验证的辅助方法,抛出异常而非退出
private void validateDate(int month, int day, int year) {
if (day < 1 || day > 31) {
throw new IllegalArgumentException("Invalid day: " + day);
} else if (month < 1 || month > 12) {
throw new IllegalArgumentException("Invalid month: " + month);
} else if (year < 2014 || year > 2024) {
throw new IllegalArgumentException("Invalid year: " + year);
}
}
public void setDay(int day) {
if (day >= 1 && day <= 31) { // 修正逻辑错误
this.day = day;
} else {
throw new IllegalArgumentException("Invalid day: " + day);
}
}
public int getDay() { return day; }
public int getMonth() { return month; }
public int getYear() { return year; }
// ... 其他方法 ...
}然后,在Order类中应用防御性拷贝:
public class Order {
private Date orderDate;
// ... 其他字段 ...
public Order(Money amount, Date date, String company, String product) {
// 防御性拷贝:在构造器中创建Date对象的副本
this.orderDate = new Date(date);
// ... 初始化其他字段 ...
}
public Date getOrderDate() {
// 防御性拷贝:返回Date对象的副本,防止外部修改内部状态
return new Date(orderDate);
}
// ... 其他方法 ...
}通过这种方式,Order类内部维护的是Date对象的独立副本。即使外部代码修改了原始的Date对象,也不会影响Order实例的内部状态。
注意事项:
不可变对象是指一旦创建,其内部状态就不能再被改变的对象。不可变对象天然免疫隐私泄露问题,因为即使外部持有其引用,也无法修改其状态。对于表示值(如日期、金额、坐标)的小型对象,不可变设计通常是更优的选择。
实现不可变对象的关键点:
示例代码:
将Date类设计为不可变对象:
final class Date { // 类声明为final
final int year, month, day; // 所有字段声明为final
public Date(int month, int day, int year) {
// 参数验证 (抛出异常)
if (day < 1 || day > 31) {
throw new IllegalArgumentException("Invalid day: " + day);
} else if (month < 1 || month > 12) {
throw new IllegalArgumentException("Invalid month: " + month);
} else if (year < 2014 || year > 2024) { // 示例范围
throw new IllegalArgumentException("Invalid year: " + year);
}
this.month = month;
this.day = day;
this.year = year;
}
// 只有Getter方法,没有Setter方法
public int getDay() { return day; }
public int getMonth() { return month; }
public int getYear() { return year; }
// 可选:重写equals(), hashCode(), toString() 以确保值语义
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Date date = (Date) o;
return year == date.year && month == date.month && day == date.day;
}
@Override
public int hashCode() {
return Objects.hash(year, month, day);
}
@Override
public String toString() {
return String.format("%04d-%02d-%02d", year, month, day);
}
}当Date类是不可变的时,Order类可以更简洁地处理它:
public class Order {
private final Date orderDate; // 如果Order本身也设计为不可变,字段可声明为final
// ... 其他字段 ...
public Order(Money amount, Date date, String company, String product) {
// 对于不可变Date对象,直接赋值是安全的,因为其状态不会改变。
// 无需防御性拷贝,因为Date对象一旦创建,其内部状态就不可修改。
this.orderDate = date;
// ... 初始化其他字段 ...
}
public Date getOrderDate() {
// 对于不可变以上就是Java中可变对象隐私泄露的防御:防御性拷贝与不可变设计指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号