title: Java generics - Don't allow subclasses
body: <p>I have a question about generics. So lets say I have 3 classes "Foo", "Bar" (which is a subclass of Foo), a class "Factory" and an interface "TestInterface". 
  I want to write a generic method, that only allows objects which "directly" implement the interface, so no subclasses. 
  It is pretty hard for me, since Java8 seems to be "smarter" than Java7.</p>
  
  <p>So heres an example: </p>
  
  <pre><code>public interface TestInterface&lt;T extends TestInterface&lt;T&gt;&gt; {
  
  }
  </code></pre>
  
  <hr>
  
  <pre><code>public class Foo implements TestInterface&lt;Foo&gt;{
  
  }
  </code></pre>
  
  <hr>
  
  <pre><code>public class Bar extends Foo {
  
  }
  </code></pre>
  
  <hr>
  
  <pre><code>public class Factory {
  
     public static &lt;T extends TestInterface&lt;T&gt;&gt; T doSth(T arg) {
         return arg;
     }
  }
  </code></pre>
  
  <p>Okay, these are my classes. Now in the <code>doSth(T arg)</code> method I want to allow Foo-objects in this case, since it's the only class which "directly" implements the Interface. </p>
  
  <p>Obviously sth like this won't compile now: </p>
  
  <pre><code>Bar b = Factory.doSth(new Bar());
  </code></pre>
  
  <p>since Bar doesnt implement <code>TestInterface&lt;Bar&gt;</code>. </p>
  
  <p>Okay my problem now is, that this line will compile without any issues: </p>
  
  <pre><code>Foo f = Factory.doSth(new Bar());
  </code></pre>
  
  <p>Even tho the generic parameter is T and T should implement the interface with its own class (sorry, dont really know how to say it, hope you know what I mean), the compiler accepts "Bar" as a parameter. </p>
  
  <p>So the compiler must behave like "okay Bar doesn't fit, but maybe a superclass would fit." And then it "sees" that it works with the superlcass "Foo". 
  And then the Bar will be treated like a Foo, since every Bar is some kind of a Foo or sth like that?? At least that's how I imagine it. </p>
  
  <p>Well, if I try to compile the line with Java7, it fails. So it seems like Java8 is a little bit smarter with the type-erasure?!</p>
  
  <p>Is there any way in Java8 to not allow subclasses, so that this won't compile?: </p>
  
  <pre><code>Foo f = Factory.doSth(new Bar());
  </code></pre>
  
  <p>Hope you understand my problem, I'm rarely writing in English. </p>
  
  <p>Greets</p>