title: Fluent API with inheritance and generics
body: <p>I'm writing a fluent API to configure and instantiate a series of "message" objects. I have a hierarchy of message types.</p>
  
  <p>To be able to access method of subclasses when using the fluent API, I used generics to parametrize the subclasses and make all fluent methods (that start with "with") return the generic type. Note that I omitted most of the body of the fluent method; a lot of configuration goes on in them. </p>
  
  <pre><code>public abstract class Message&lt;T extends Message&lt;T&gt;&gt; {
  
      protected Message() {
  
      }
  
      public T withID(String id) {
          return (T) this;
      }
  }
  </code></pre>
  
  <p>The concrete subclasses redefine the generic type similarly.</p>
  
  <pre><code>public class CommandMessage&lt;T extends CommandMessage&lt;T&gt;&gt; extends Message&lt;CommandMessage&lt;T&gt;&gt; {
  
      protected CommandMessage() {
          super();
      }
  
      public static CommandMessage newMessage() {
          return new CommandMessage();
      }
  
      public T withCommand(String command) {
          return (T) this;
      }
  }
  
  public class CommandWithParamsMessage extends
      CommandMessage&lt;CommandWithParamsMessage&gt; {
  
      public static CommandWithParamsMessage newMessage() {
          return new CommandWithParamsMessage();
      }
  
      public CommandWithParamsMessage withParameter(String paramName,
          String paramValue) {
          contents.put(paramName, paramValue);
          return this;
      }
  }
  </code></pre>
  
  <p>This code works, i.e. I can instantiate any of the classes and use all fluent methods:</p>
  
  <pre><code>CommandWithParamsMessage msg = CommandWithParamsMessage.newMessage()
          .withID("do")
          .withCommand("doAction")
          .withParameter("arg", "value");
  </code></pre>
  
  <p>Calling the fluent methods in any order is a major goal here.</p>
  
  <p>However, the compiler warns that all <code>return (T) this</code> are unsafe. </p>
  
  <blockquote>
    <p>Type safety: Unchecked cast from Message to T</p>
  </blockquote>
  
  <p>I'm unsure how I could reorganize the hierarchy to make this code truly safe. Even though it works, the use of generics in this fashion feels really convoluted. 
  Especially, I'm not able to foresee situations where runtime exceptions will happen if I just ignore the warnings.
  There will be new message types, so I need to keep the code extensible.
  If the solution is to avoid inheritance altogether I would also like to obtain suggestion of alternatives.</p>
  
  <p>There are <a href="https://stackoverflow.com/q/7959335/1089062">other</a> <a href="https://stackoverflow.com/q/7354740/1089062">questions</a> here on SO that address a similar issue. They point to a solution where all intermediate classes are abstract and declare a method like <code>protected abstract self()</code>. Still, in the end it's not safe.</p>