How to use setter instead of constructor for final variable?

I am parsing an XML file where one of the fields that I want to be unchanged, the ID, must be set after creating the object. Should I set its value to null and throw an exception in the setID () method if ID! = Null?

Edit: I parse the XML file, and at the beginning I create an object whose fields and objects are populated using the information in the XML file. I want to be able to set the identifier, which should be immutable, after creating the root object.

Edit: changed “final” to “immutable” because it is really what I mean semantically. (Excuse me:()

+3
source share
8 answers

The final fields, by definition, do not change after the construction of the object. If what you really mean is that you want the field to be set once, you can simply initialize the field to null if the installer throws an exception for that field if the field is no longer null.

+6
source

The most common use case is to use the builder pattern . You create an object using setters, and then when it is ready, you create an immutable object using the builder as a template.

+14
source

. .

+9

Builder, Java 2nd Edition 2.

, Builder, ( ) . build(). Builder () , . .

:

public class Foo {
  public static class Builder {
    public Foo build() {
      return new Foo(this);
    }

    public Builder setId(int id) {
      this.id = id;
      return this;
    }

    // you can set defaults for these here
    private int id;
  }

  public static Builder builder() {
      return new Builder();
  }

  private Foo(Builder builder) {
    id = builder.id;
  }

  private final int id;

  // The rest of Foo goes here...
}

Foo, - :

Foo foo = Foo.builder()
    .setId(id)
    .build();

, :

// I don't know the ID yet, but I want a place to store it.
Foo.Builder fooBuilder = Foo.builder();
...
// Now I know the ID:.
fooBuilder.setId(id);
...
// Now I'm done and want an immutable Foo.
Foo foo = fooBuilder.build();

build() Builder.

, . API - .

+7

final. setID(), ID != null - . , , - ?

+1

final, . , - .

class Foo {

  private Bar x;

  void setX(Bar x) {
    if (x == null)
      throw new IllegalArgumentException();
    if (this.x != null)
      throw new IllegalStateException();
    this.x = x;
  }

}

Foo . AtomicReference synchronize.

, null x, private, dummy Bar null.

0

, xml XStream, . , , , , .

aviod setId, , , - . , , , .

XML , factory, .

, "" , , , .

0

, , "". "".

: , , - - . , , , , . , - .

- . . " " "" ".

0

Source: https://habr.com/ru/post/1754468/


All Articles