我与龙目岛两难境地,那些谁知道这个工具知道,这是很容易声明getter和setter方法,但是当涉及到日期和类别,我们如何才能声明它们一成不变?
THX和亲切的问候!
龙目岛提供@Wither,允许以某种方式来缓解不可变对象的创建。然而,这并不包括你提到的情况。
您将有管理的对象自己的不变性,并使用龙目岛的所有其他情况。
此外,这是一个例子,如何实现ImmutableObject
与Date
和Collection
:
public final class ImmutableObject {
private final Collection<String> collection;
private final Date date;
public ImmutableObject(final Collection<String> options, final Date createdAt) {
this.collection = ImmutableList.copyOf(options); // guava's immutable list
this.date = new Date(date); // must be copied to prevent caller from modifying it
}
public Date getDate() {
return new Date(date); // Date is mutable
}
public Collection<String> getCollection() {
return collection; // already immutable copy
}
}