public final class Period implements Serializable {
private final Date start;
private final Date end;
public Period(Date start, Date end) {
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
if (this.start.compareTo(this.end) > 0) {
throw new IllegalArgumentException(start + " after " + end);
}
}
public Date start() {
return new Date(start.getTime());
}
public Date end() {
return new Date(end.getTime());
}
// ...
}
public class MutablePeriod {
public final Period period;
public final Date start;
public final Date end;
public MutablePeriod() {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
// ์ ํจํ Period ์ธ์คํด์ค๋ฅผ ์ง๋ ฌํ
out.writeObject(new Period(new Date(), new Date()));
// ์ ์์ ์ธ ์ด์ ๊ฐ์ฒด ์ฐธ์กฐ
// ์ด๋ฏธ ์ง๋ ฌํ๋ ๊ฐ์ฒด์ธ Period ๋ด๋ถ์ Date ํ๋๋ก์ ์ฐธ์กฐ๋ฅผ ์ถ๊ฐ
byte[] ref = {0x71, 0, 0x7e, 0, 5};
bos.write(ref); // ์์ ํ๋
ref[4] = 4;
bos.write(ref); // ์ข ๋ฃ ํ๋
// Period ์ธ์คํด์ค ์ญ์ง๋ ฌํ
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bos.toByteArray()));
period = (Period) in.readObject();
start = (Date) in.readObject(); // Period ๋ด๋ถ์ Date ๊ฐ์ฒด ์ฐธ์กฐ
end = (Date) in.readObject(); // Period ๋ด๋ถ์ Date ๊ฐ์ฒด ์ฐธ์กฐ
// ๊ฒฐ๊ณผ์ ์ผ๋ก start์ end๋ period์ ๋ด๋ถ Date ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ๊ฒ ๋จ
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
public class Main {
public static void main(String[] args) {
MutablePeriod mp = new MutablePeriod();
Period p = mp.period;
Date pEnd = mp.end; // pEnd๋ p์ ๋ด๋ถ Date ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐ
pEnd.setYear(78); // pEnd ๋ณ๊ฒฝ -> p๋ ํจ๊ป ๋ณ๊ฒฝ๋จ
System.out.println(p);
}
}