• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Generated builder example
2
3
4For the code shown in the [builder documentation](builders.md), the following is
5typical code AutoValue might generate:
6
7```java
8import javax.annotation.Generated;
9
10@Generated("com.google.auto.value.processor.AutoValueProcessor")
11final class AutoValue_Animal extends Animal {
12  private final String name;
13  private final int numberOfLegs;
14
15  private AutoValue_Animal(
16      String name,
17      int numberOfLegs) {
18    this.name = name;
19    this.numberOfLegs = numberOfLegs;
20  }
21
22  @Override
23  String name() {
24    return name;
25  }
26
27  @Override
28  int numberOfLegs() {
29    return numberOfLegs;
30  }
31
32  @Override
33  public String toString() {
34    return "Animal{"
35        + "name=" + name + ", "
36        + "numberOfLegs=" + numberOfLegs
37        + "}";
38  }
39
40  @Override
41  public boolean equals(Object o) {
42    if (o == this) {
43      return true;
44    }
45    if (o instanceof Animal) {
46      Animal that = (Animal) o;
47      return (this.name.equals(that.name()))
48           && (this.numberOfLegs == that.numberOfLegs());
49    }
50    return false;
51  }
52
53  @Override
54  public int hashCode() {
55    int h = 1;
56    h *= 1000003;
57    h ^= this.name.hashCode();
58    h *= 1000003;
59    h ^= this.numberOfLegs;
60    return h;
61  }
62
63  static final class Builder extends Animal.Builder {
64    private String name;
65    private Integer numberOfLegs;
66
67    Builder() {
68    }
69
70    @Override
71    Animal.Builder setName(String name) {
72      if (name == null) {
73        throw new NullPointerException("Null name");
74      }
75      this.name = name;
76      return this;
77    }
78
79    @Override
80    Animal.Builder setNumberOfLegs(int numberOfLegs) {
81      this.numberOfLegs = numberOfLegs;
82      return this;
83    }
84
85    @Override
86    Animal build() {
87      String missing = "";
88      if (this.name == null) {
89        missing += " name";
90      }
91      if (this.numberOfLegs == null) {
92        missing += " numberOfLegs";
93      }
94      if (!missing.isEmpty()) {
95        throw new IllegalStateException("Missing required properties:" + missing);
96      }
97      return new AutoValue_Animal(
98          this.name,
99          this.numberOfLegs);
100    }
101  }
102}
103```
104