让我建议您一点更优雅的决定。第一个变体(不引发异常):
public class Example { private Long id; // Constructors and other variables and methods deleted for clarity public long getId() { return id; } public void setId(long id) { this.id = this.id == null ? id : this.id; }}第二种变体(引发异常):
public void setId(long id) { this.id = this.id == null ? id : throw_(); } public int throw_() { throw new RuntimeException("id is already set"); }


