title: Is it possible to detect comparison of incompatible types with the Java type system?
body: <p>I'm trying to write a helper function to compare two types in a typesafe way:</p>
  
  <pre><code>typesafeEquals("abc", new Integer(42)); // should not compile
  </code></pre>
  
  <p>My first straightforward attempt failed:</p>
  
  <pre><code>&lt;T&gt; boolean typesafeEquals(T x, T y) { // does not work!
      return x.equals(y);
  }
  </code></pre>
  
  <p>Well, the problem is that <code>T</code> can be deduced to be an <code>Object</code>. Now, I wonder if it is impossible to implement <code>typesafeEquals</code> in the Java type system.</p>
  
  <p>I know that there are tools like FindBugs find can warn about comparison of incompatible types. Anyway it would be interesting to either see a solution without external tools or an explanation why it is impossible.</p>
  
  <hr>
  
  <p><strong>Update:</strong> I think the answer is that it is impossible. I have no proof to support that claim, though. Only that it seems to be difficult to come up with a solution that works for all cases.</p>
  
  <p>Some answers come close, but I believe the type system of Java does not support to solve the problem in all generality.</p>