title: Generic Builder in Java
body: <p>I created a builder for a lookup table and using it as shown below.</p>
  
  <pre><code>public class RaceCodeDataBuilder {
  
      private RaceCode raceCode;  
  
      public RaceCodeDataBuilder() {
          raceCode = new RaceCode();
      }
  
      public RaceCodeDataBuilder code(String code) {
          raceCode.setCode(code);     
          return this;
      }
  
      public RaceCodeDataBuilder displayName(String displayName) {
          raceCode.setDisplayName(displayName);
          return this;
      }
  
      public RaceCode build() {
          return raceCode;
      }
  
  }
  </code></pre>
  
  <p><strong>Using this builder in a test:</strong> </p>
  
  <pre><code>   RaceCode mockRaceCode = new RaceCodeDataBuilder()
                           .code("2054-5")
                           .displayName("Black or African American")
                           .build();
  </code></pre>
  
  <p>I am expecting lot more similar builders for other look up tables such as StateCodeBuilder, GenderCodeBuilder and all of them have just "code" and "displayName", similar to above builder.</p>
  
  <p><strong>I want to create a generic builder and avoid creating several builder classes doing the same job with different name.</strong></p>
  
  <p>I attempted something in generics but I am way off..</p>
  
  <pre><code>public class CodeDataBuilder&lt;T&gt;{
  
      private T t;    
  
      public CodeDataBuilder(T t) {
          this.t = t;
      }
  
      public CodeDataBuilder code(String code) {
          raceCode.setCode(code);     // Cant write T.setCode here for obvious resons
          return this;
      }
  
      public CodeDataBuilder displayName(String displayName) {
          raceCode.setDisplayName(displayName); // Cant write T.setDisplayNamehere for obvious resons
          return this;
      }
  
      public T build() {
          return t;
      }
  
  }
  </code></pre>
  
  <p>Can someone help me with that?</p>
  
  <p>Thank you.</p>