title: Have a class implement an unspecified generic interface in java
body: <p>I have the following "generic" question</p>
  
  <p>Here is a my generic message interface.  </p>
  
  <pre><code>public interface Message&lt;P,R&gt; {  
      void setParams(P Params); // and the corresponding getter  
      void setResults(R results);  
  }  
  </code></pre>
  
  <p>For simplicity reasons I would like to specify a number (of interfaces) of messages by predefining  the parameter and result type. So that if you work with message X you know what the params and result type are.</p>
  
  <p>Such as</p>
  
  <pre><code>public interface MyMessage extends Message&lt;String,String&gt; {}  
  </code></pre>
  
  <p>That works fine, now I would like to have a common base class which can implement any of the messages.</p>
  
  <pre><code>public class BaseMessage&lt;P,R&gt; implements Message&lt;P,R&gt; {
      P param;
      R results;
      // base implementation
  }
  </code></pre>
  
  <p>The problem of the above now is that I can't have a BaseMessage which implements MyMessage.</p>
  
  <p>Multiple attempts like</p>
  
  <pre><code>public class BaseMessage&lt;T extends BaseMessage&lt;P,R&gt;&gt; implements Message&lt;P,R&gt; 
  </code></pre>
  
  <p>or</p>
  
  <pre><code>public class BaseMessage&lt;? extends BaseMessage&lt;P,R&gt;&gt; implements Message&lt;P,R&gt; 
  </code></pre>
  
  <p>will not work, as the compiler complains that P and R are not bound.
  Introducing them as additional parameters works again, but at that moment the resulting class will not be cast-able to BaseMessage or the desired MyMessage. </p>
  
  <pre><code>public class BaseMessage&lt;P,R,T extends BaseMessage&lt;P,R&gt;&gt; implements Message&lt;P,R&gt; 
  </code></pre>
  
  <p>I would like to have a generic factory method, which would be given the message class, the parameter and the result object and will return an instance of BaseMessage which implements the MyMessage interface. Like in the follwing</p>
  
  <pre><code>public static &lt;P, R, T extends Message&lt;P,R&gt;&gt; T factory(Class&lt;T&gt; clazz,P p,R r) {
      T a = (T) new BaseMessage&lt;P,R&gt;();
      // create a BaseMessage which which Implements T
      a.setParams(p);
      a.setResults(r);
      return a;
  }
  </code></pre>
  
  <p>Anyone encountered a similar problem, or is that something not possible in Java?</p>
  
  <p>Thanks!</p>