如何用 Lombok 定义 Date And Collections 不可变?

How to define with Lombok Date And Collections immutable?

我对lombok进退两难了,知道这个工具的都知道声明getters和setters很容易,但是涉及到Dates和Collections,我们怎么才能声明它们不可变呢?

谢谢和亲切的问候!

Lombok 提供 @Wither 允许以某种方式简化不可变对象的创建。但是,它不包括您提到的情况。

您必须自己管理对象的不可变性,并在所有其他情况下使用 Lombok。

此外,这是一个如何使用 DateCollection 实现 ImmutableObject 的示例:

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
    }
}