How to create a variable that can be set only once but isn't final in Java

后端 未结 12 1599
感情败类
感情败类 2020-12-14 05:43

I want a class that I can create instances of with one variable unset (the id), then initialise this variable later, and have it immutable after initial

12条回答
  •  醉话见心
    2020-12-14 06:39

    I have this class, similar to JDK's AtomicReference, and I use it mostly for legacy code:

    import static com.google.common.base.Preconditions.checkNotNull;
    import static com.google.common.base.Preconditions.checkState;
    
    import javax.annotation.Nonnull;
    import javax.annotation.concurrent.NotThreadSafe;
    
    @NotThreadSafe
    public class PermanentReference {
    
        private T reference;
    
        public PermanentReference() {
        }
    
        public void set(final @Nonnull T reference) {
            checkState(this.reference == null, 
                "reference cannot be set more than once");
            this.reference = checkNotNull(reference);
        }
    
        public @Nonnull T get() {
            checkState(reference != null, "reference must be set before get");
            return reference;
        }
    }
    

    I has single responsibilty and check both get and set calls, so it fails early when client code misuse it.

提交回复
热议问题