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

后端 未结 12 1580
感情败类
感情败类 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:31

    Here's the solution I came up with based on mixing some of the answers and comments above, particularly one from @KatjaChristiansen on using assert.

    public class Example {
    
        private long id = 0L;
        private boolean idSet = false;
    
        public long getId() {
            return id;
        }
    
        public void setId(long id) {
            // setId should not be changed after being set for the first time.
            assert ( !idSet ) : "Can't change id from " + this.id + " to " + id;
            this.id = id;
            idSet = true;
        }
    
        public boolean isIdSet() {
            return idSet;
        }
    
    }
    

    At the end of the day, I suspect that my need for this is an indication of poor design decisions elsewhere, and I should rather find a way of creating the object only when I know the Id, and setting the id to final. This way, more errors can be detected at compile time.

提交回复
热议问题